Unable to retrieve new API data when Vue.js script setup parameters change

I am working on fetching data from jsonplaceholder using Axios in Vue. I have created a limit with a select input where the user can specify how many posts they want to see. The default number of posts displayed is 10. Initially, when the page loads, everything works correctly and the user can see 10 posts. However, when the user tries to change the limit, it still displays only 10 posts. Can someone please help me troubleshoot this issue? Below is my code:

<template>

  <section class="text-center">
    <div v-if="loading" class="spinner-border text-center text-primary" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </section>

  <router-link class="btn btn-primary" :to="{name:'createPost'}">Add Post</router-link>

  <select v-model="selected" class="form-control" >
    <option disabled value="">Choose number of posts</option>
    <option value="10">10 Posts</option>
    <option value="20">20 Posts</option>
    <option value="50">50 Posts</option>
    <option value="100">All Posts</option>
  </select>
  <section v-if="!loading" class="col-4" v-for="post in posts" :key="post.id">
    <Card :post="post" />
  </section>


</template>

<script setup>
import axios from 'axios'
import {ref} from "vue";
import Card from "@/components/posts/Card";

let loading = ref(true)
let posts = ref([])
let selected =ref('10')

 function userReq(){
  // Using Axios to fetch data based on the selected limit
  axios.get(`https://jsonplaceholder.typicode.com/posts?_limit=${selected.value}`)
      .then(response=> {
        posts.value = response.data
        loading.value=false
        console.log('response',response)
      })
      .catch(()=>console.log('error'))
}


userReq()

</script>

<style scoped>

</style>

Answer №1

Have you tried calling the fetch method after changing the value? It seems like it's only triggered on the initial component load. You can update your select code like so:

 <select v-model="selected" class="form-control" @change="userReq">
    <option disabled value="">choose number of posts</option>
    <option value="10">10 Posts</option>
    <option value="20">20 Posts</option>
    <option value="50">50 Posts</option>
    <option value="100">All Posts</option>
  </select>

Make sure to add @change="userReq" to trigger the userReq function whenever a new value is selected and update your posts accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What about those ready-made HTML components that have not been revealed yet?

If I have a form with property elements that need to be duplicated, and each property element is a div containing input elements. When the user clicks on an "Add Properties" button, I want another instance of this properties element to be created. The que ...

Encountered an issue: Error message stating that a Handshake cannot be enqueued as another Handshake has already been enqueued

I am currently working on setting up a node.js server to handle POST requests that involve inserting data into two separate MySQL tables. Below is the code snippet for my node.js server: let mysql = require("mysql"); const http = require('h ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...

Leveraging AJAX to send a form filled with dynamic content to multiple destinations

I have a hidden form that needs to be submitted to two different locations. The form is automatically filled using the .val method in jQuery. How can I write the ajax script to submit this form to two different locations? Is it possible to do this without ...

Manipulate Nested Objects using an Array of Keys

Currently, I am developing a recursive form using React and MUI that is based on a nested object. Throughout this process, it is crucial for me to keep track of the previous keys as I traverse through the recursion. As users interact with the form and mak ...

Unable to locate object for property 'setAttribute' and thus it is undefined

I am attempting to create an accordion using the code below. It works perfectly when the tags are placed together. However, I wish to insert an element inside a different tag elsewhere on the page. <dt> <li class="nav-item" i ...

Looking to swap an image on mouseover using vue.js?

With Vue.js, I can link an image to an img tag using this syntax: <img v-bind:src="myimage" /> Is there a way to specify a different image that will show up when hovering over the original image using Vue.js? ...

Exploring VueJS by enhancing lifecycle hooks in each component

My app features a loader screen that displays before the content is rendered, and then disappears once everything has loaded. While this setup works well for a few components or views, I am finding it tedious to add this functionality to every single one. ...

Compiling SCSS to CSS in Vue.js is a breeze

I am working on a vue js project that includes scss files. My goal is to compile these scss files into css and store them in the public folder. How can I achieve this? Should I make changes to the vue.config.js file? const path = require('path'); ...

Changing the div background color based on the status of the `.play()` function

I need assistance with changing the background color of a div based on whether an audio file is playing or not. $('.uprow2').on('click', function() { $('#karma')[0].play(); }); .uprow2 { width: 680px; height: 60px; ...

Incorporate several websites into a React application without using iframes

After developing a React application with create-react-app, I attempted to embed another website onto the app using an iframe. Everything worked perfectly until I wanted to resize the iframe to fit the page, resulting in a Blocked a frame with origin from ...

Troubleshooting: Issue with Firestore & Vue Integration - Retaining Data from Function Wrapper

Within my utility file labeled as "FbUtils.js", I have the following code snippet: getUserById(someUserId) { firebase .firestore() .collection("users") .doc(someUserId) .get() .then((snapshot) => { const res = { userId: someUserId, data: s ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

Password validation with Mongoose customization

I'm working on creating a Schema using mongoose, but I'm facing some challenges when it comes to implementing custom validation for the password. The password should meet the following criteria: It must contain at least one special character ...

The checkbox is not showing the check mark accurately

I am currently working on a React form where I am trying to retrieve the status of a checkbox element from local storage using the useEffect hook. const [checkbox, setCheckbox] = useState(false); useEffect(() => { setCheckbox(localStorage.getItem(&ap ...

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

One method I use to retrieve ajax data and assign it before rendering the view

Despite putting the ajax.get in the created function, I am still unable to retrieve the ap_name value. This issue is related to vue.js created: function () { ajax.get('/envs').then(function (res) { this.apName = res.AP_NAME; ...

Decreased Performance in Vue Threejs with Larger JSON Data Sets

I am currently upgrading a legacy Three.js project from Angular 1.5 to Vue 2.6. The project is used for visualizing objects in JSON file format and I'm experiencing a drop in frame rate, going from ~60FPS in Angular to ~12FPS in Vue when loading large ...