Strategies for Refreshing a Component After Modifying Data in the Store

Having trouble updating my table component when the data in my store changes. I have a simple table using v-for as shown below:

<tr v-for="d in getDatas" v-bind:key="d.id">

and buttons to navigate between pages:

<button class="fa fa-chevron-left" @click="previousPage"/>
<button class="fa fa-chevron-right" @click="nextPage"/>

I load data into my datas before opening the component with the table, and retrieve this data from the store like so:

  computed: {
    getDatas () {
      return this.$store.getters.getDatas;
    }
  },

but how can I update my store with new data when clicking on the nextPage or previousPage button? Below are my methods:

  methods: {
      ...mapActions(["fetchDatas"]), //this is my action
      nextPage() {
        this.currentPage += 1;
      },
      previousPage() {
        if(this.currentPage != 1) {
          this.currentPage -= 1;
        }
      },

and my action:

    async fetchDatas({ commit },{ currentPage}) {
        const data = await fetch(`someURL&perPage=${currentPage}`);
        const response = await data.json();
        commit('setData', response);
    }

So, how do I reload the component and my store when clicking on next/previousPage?

Answer №1

Your current setup includes a computed property which automatically updates when the store changes. To switch pages, you simply need to trigger the action within your methods.

nextPage() {
   this.currentPage += 1;
   this.fetchDatas(this.currentPage);
},
previousPage() {
   if(this.currentPage != 1) {
      this.currentPage -= 1;
      this.fetchDatas(this.currentPage);
   }
},

If there is no specific reason for requiring an Object parameter in the action, consider removing the curly braces altogether:

async fetchDatas({ commit }, currentPage) {
...

Otherwise, you would have to call it using

this.fetchData({currentPage: this.currentPage})
.

Answer №2

To ensure that the getDatas action is triggered whenever the current page variable changes, you can set up a watch on it. This way, clicking the buttons to change the page will automatically fire the action again.

You can define the watch like this:

watch: {
        currentPage: function (newPage) {
            this.$store.dispatch('fetchDatas', newPage)
        },
}

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

Expanding the functionality of express.Router

Can someone help me with how to extend the functionality of express.Router? I attempted the following: class Test extends express.Router() { }; However, I encountered an error when trying this in Express. Does anyone have a solution for this issue? ...

Ways to retrieve the clicked item's index in a jQuery collection without using the index() method

Is there a way to obtain the index of clicked elements easily? var $inputs = $("input"); $inputs.click(function() { console.log($(this).index()) }); This method correctly works for the structure below: div>(input+input+input) However, I am encoun ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

Using Ramda to retrieve objects from an array by comparing them with each element in a separate array

I have two arrays: ids = [1,3,5]; The second array is: items: [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ]; I ...

transform the stationary drawing to the top and left position at coordinate (0,0)

Exploring canvas has led me to encounter a puzzling issue with the translate method. While working on this fiddle http://jsfiddle.net/claireC/ZJdus/4/, my goal was to have the drawing move and bounce off all four walls. However, I noticed that it would no ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

Navigate to a fresh web page without encountering any script loading issues

I am currently working on a web application that loads new pages without requiring the browser to reload. While some pages load perfectly fine, others are causing errors due to missing scripts. The code snippet below is used to load a new page: function lo ...

Dealing with a void method in a React unit test by treating it as an object's property

How can I pass a value to a function in an interface to trigger a click event on an element? I have a React component that I want to write unit tests for: const VariantItem = (props: VariantItem): ReactElement => { return ( <div key={props.produc ...

The width and height properties in the element's style are not functioning as expected

let divElement = document.createElement("div"); divElement.style.width = 400; divElement.style.height = 400; divElement.style.backgroundColor = "red"; // num : 1 divElement.innerText = "Hello World "; // num : 2 document.body.append(divElement); // Af ...

Displaying a collection of items using ReactJS

Hey there! I have an array of objects containing comments for a particular item, and I only want to display the first 10 on the page. Below that list, I'm looking to add a button that allows users to see the next set of 10 comments when clicked. It&a ...

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

The AuthGuard (Guard decorator) is unable to resolve its dependencies according to Nest

My AuthGuard is responsible for checking the JWT token in controllers. I am trying to use this Guard in controllers to verify authentication, but I encountered the following error: Nest cannot resolve dependencies of the AuthGuard (?, +). Please ensur ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

What is the best way to set up the correct pathway for displaying the image?

I'm currently facing a challenge with displaying an image from my repository. The component's framework is stored in one library, while I'm attempting to render it in a separate repository. However, I am struggling to determine the correct p ...

Is utilizing web workers for numerous simultaneous intensive computations a viable strategy?

Is it necessary to create multiple worker files for each concurrent heavy calculation with the same formula, or can I work with just one? ...

GraphQL query must receive an object for the Mongo filter, but instead, it received a string

Is there a way to pass a filter option to MongoDB using GraphQL? I attempted to do it in a certain way, but encountered an error that stated: "message": "Parameter \"filter\" to find() must be an object, got {email: "<a href="/cdn-cgi/l/email ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...