Nuxt Vuex global state update does not cause v-for loop components to re-render

I am struggling to effectively use Vuex global state with re-rendering child components in Vue.js. The global state is being mutated, but the data does not update in the v-for loop.

Initially, all data is rendered correctly. However, when new data is introduced, the component in /blog fails to reflect the changes.

Here is a snippet of the code:

/store/index.js

export const state = () => ({
  allData: [],
})
export const getters = {
  getAllData: (state) => state.allData,
}
export const mutations = {
  GET_DATAS(state, payload) {
    state.allData = payload
  },
  UPDATE_DATA(state, payload) {
    const item = state.allData[payload.index]
    Object.assign(item, payload)
  },
}
export const actions = {
  getDatas({ commit, state }, payload) {
    return fetch(`URL_FETCH`)
      .then((data) => data.json())
      .then((data) => {
        commit('GET_DATAS', data)
      })
      .catch((err) => console.log(err))
  },
  updateData({ commit, state }, payload) {
    commit('UPDATE_DATA', payload)
  },
}

In /layouts/default.vue

beforeCreate() {
  this.$store.dispatch('getDatas').then(() => {
    connectSocket()
  })
},
methods: {
  connectSocket() {
    // connect & receive messages from socket
    // receive messages from socket
    this.$root.$emit('updateData', {
      index: 12,
      price: 34,
      change: 56,
      percent: 78,
    })
  },
},

And in /pages/blog/index.vue

<template>
  <div>
    <div
      v-for="index in getAllData"
      :key="index.name"
      class="w-100 grid-wrapper"
    >
      <div>{{ index.price }}</div>
      <div>{{ index.change }}</div>
      <div>{{ index.percent }}</div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
    ...mapGetters(['getAllData']),
  },
  mounted() {
    this.$root.$on('updateData', (item) => {
      this.$store.dispatch('updateData', {
        index: item.index,
        price: item.price,
        percent: item.percent,
        change: item.change,
      })
    })
  },
}
</script>

Answer №1

Below is a comprehensive example showcasing the efficient use of Vuex to load data into a Nuxt app following best practices.

/pages/index.vue

<template>
  <div>
    <main v-if="!$fetchState.pending">
      <div v-for="user in allData" :key="user.id" style="padding: 0.5rem 0">
        <span>{{ user.email }}</span>
      </div>
    </main>
    <button @click="fakeUpdate">Update the 2nd user</button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  data() {
    return {
      mockedData: {
        name: 'John Doe',
        username: 'jodoe',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a13050605191d0b0d2a0d070b030644090507">[email protected]</a>',
        phone: '1-770-736-8031 x56442',
        website: 'hildegard.org',
      },
    }
  },
  async fetch() {
    await this.setAllData()
  },
  computed: {
    ...mapState(['allData']),
  },
  methods: {
    ...mapActions(['setAllData', 'updateData']),

    fakeUpdate() {
      this.updateData({ index: 1, payload: this.mockedData })
    },
  },
}
</script>

/store/index.js

import Vue from 'vue'

export const state = () => ({
  allData: [],
})

export const mutations = {
  SET_ALL_DATA(state, payload) {
    state.allData = payload
  },
  UPDATE_SPECIFIC_DATA(state, { index, payload }) {
    Vue.set(state.allData, index, payload)
  },
}

export const actions = {
  async setAllData({ commit }) {
    try {
      const httpCall = await fetch('https://jsonplaceholder.typicode.com/users')
      const response = await httpCall.json()
      commit('SET_ALL_DATA', response)
    } catch (e) {
      console.warn('error >>', e)
    }
  },
  updateData({ commit }, { index, payload }) {
    commit('UPDATE_SPECIFIC_DATA', { index, payload })
  },
}

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

Utilizing a single delete function for a post request in jQuery or a PHP request

Seeking guidance on how to achieve a specific task. I have a controller that loads a view containing a table listing pages from my database. Each row in the table has an icon that, when clicked, performs one of two actions. If the user does not have javas ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

Having trouble with Node.js executing commands in the console

I've been following some tutorials on YouTube to learn how to create a real-time chat using Node.js from the phpacademy channel. Currently, I'm stuck at the step where I need to run my server.js file in the console. When I enter the command ...

The unexpected end of input error is caused by an Ajax call that returns a SyntaxError

I recently developed a basic notepad application where users can retrieve a specific file (which essentially translates to a row from MySQL) in order to make edits. When the form is submitted directly to the PHP file without preventing the default behavi ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

AngularJS encountered an error: [$injector:modulerr] problem occurred during code execution

Hey there! I've been trying to set up a pop-up feature in Angular, but unfortunately, I keep encountering an error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fa ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...

Tips for sending a string as HTML content in VueIn Vue, you can send a string as

I am attempting to pass the value for exp by using this code snippet. However, the form of selectedChannel.explanation appears as "channel name". Is there a way for me to display exp as channel name? computed: { channel: { get() { ...

Manipulating DOM elements using JavaScript Vanilla with the Jquery <<S.fn.init [selector]>> framework

I have a project where I need to switch the logic written in jQuery to vanilla JavaScript. Here is an overview of my code: I am using the keydown event on an input element to trigger a function that searches an API based on the input value. var selectedU ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

Trouble with Fullcalendar v4: Unable to use addEvent() function in a customized view

Currently, I am utilizing fullcalendar v4 (accessible at https://fullcalendar.io/) and facing an issue where I need to refresh the dropped event in a custom view called 'timeGridSixMonth'. var calendar = new FullCalendar.Calendar(calendarEl, { ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

Display information retrieved from a PHP request on an AngularJS webpage

I could really use some assistance upfront! I am facing issues with displaying the data retrieved from PHP on an AngularJS website. I have reviewed previous discussions on this topic, but unfortunately, none of them have proven helpful. From what I can te ...

Vue's v-model functionality encounters issues when navigating back and forth in the browsing history

Below is a sample of code from the local index.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">< ...

Javascript code has been implemented to save changes and address resizing problems

Code Snippet: <script> function showMe(){ document.querySelector('#change').style.display = ''; document.querySelector('#keep').style.display = 'none' document.querySelector('#change1').style.d ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Issue with Bootstrap 3 dropdown not receiving updates

My goal is to dynamically populate a bootstrap 3 dropdown menu from a MySQL database. Everything works perfectly the first time I load the data. However, when I add more rows to the database, they do not automatically show up in the dropdown. Only after ...