Troubleshooting Vue.js and Vuex: Resolving Issues with View Updates

Currently, I am experimenting with Vuejs and Vuex. However, I am facing an issue when trying to update the view (vuejs) after making an AJAX call. Strangely, the view does not update when using arrays, objects, or booleans. Surprisingly, if I update a string via the store commit, it is properly reflected in the view. In the Vue developer tool, I can see that the Vuex / store is updating correctly. Interestingly, as soon as I make a change to any part of example.vue, hot reloading kicks in and the data is displayed.

I believe I must be missing something small but crucial, as I cannot seem to figure out what is required to trigger the update.

For this setup, I am utilizing the vue-cli tool and have included Axios and Vuex through npm.

This is the code I am working on:

store.js
import Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export const StoreExample = new Vuex.Store({
    state: {
        customers: [],
        isLoading: false,
    },

    getters: {
        getCustomers: state => state.customers,
        isLoading: state => state.isLoading,
    },

    mutations: {
        setCustomers(state, payload) {
            state.customers.push(payload)
        },

        setLoading(state, payload) {
            state.isLoading = payload
        }
    },

    actions: {
        fetchCustomers({state, commit}) {
            commit('setLoading', true)
            axios.get('https://api.myjson.com/bins/rkyih')
            .then(response => {
                commit('setCustomers', response.data)
                commit('setLoading', false)
            })
            .catch(e => {
                console.error(e)
                commit('setLoading', false)
            })
        }
    },

    strict: process.env.NODE_ENV !== 'production'
})

main.js

import Vue from 'vue'
import Vuex from 'vuex'
import { StoreExample } from './store/store.js'
import App from './App'

Vue.use(Vuex)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store: StoreExample,
  components: { App },
  template: '<App/>'
})

example.vue

<template>
    <div>
        {{isLoading}}
        {{getCustomers}}
    </div>

</template>

<script>
    import { mapGetters } from 'vuex'

    export default {
        name: 'example',

        created() {
            this.$store.dispatch('fetchCustomers')
        },

        computed: {
            ...mapGetters([
                'getCustomers',
                'isLoading'
            ])
        }
    }
</script>

App.vue

<template>
  <div id="app">
    <example/>
  </div>
</template>

<script>
import example from './components/example'

export default {
  name: 'App',

  components: {
    example
  }
}
</script>

Answer №1

Although I couldn't reproduce your issue, I was able to utilize your code and construct a functional example that closely resembles 90% of your original code.

Key findings from this example:

  • I confirmed that there is no significant variance between using getters or directly accessing the state.
  • It was evident that the problem you encountered wasn't related to array.push(), as Vue automatically handles Array.push() for triggering updates.
  • In place of axios, I opted for fetch for simplicity since it functions in a similar manner.

const store  = new Vuex.Store({
  state: {
    customers: [],
    isLoading: false,
  },
  getters: {
    gCustomers: state => state.customers,
    gIsLoading: state => state.isLoading,
  },
  mutations: {
    setCustomers(state, payload) {
      state.customers = payload
    },
    setLoading(state, payload) {
       state.isLoading = payload
    },
    addCustomer(state, payload) {
      state.customers.push(payload)
    },
    resetCustomers(state) {
      state.customers = [];
    }
  },
  actions: {
    fetchCustomers({ state, commit }) {
      return fetch('https://api.myjson.com/bins/rkyih')
        .then(res => res.json())
        .then(response => {
          commit('setCustomers', response)
          commit('setLoading', false)
        })
        .catch(e => {
          console.error(e)
          commit('setLoading', false)
        });
    }
  },
});

const app = new Vue({
  store,
  el: '#app',
  data: {
    dataId: '',
    isActive: '',
    age: '',
    firstName: '',
    lastName: ''
  },
  computed: {
    ...Vuex.mapGetters([
      'gIsLoading', 'gCustomers' 
    ]),
    ...Vuex.mapState([
      'customers', 'isLoading'
    ])
  },
  methods: {
    ...Vuex.mapActions({
      getData: 'fetchCustomers'
    }),
    ...Vuex.mapMutations({
      resetData: 'resetCustomers'
    }),
    addCustomer() {
      this.$store.commit('addCustomer', {
        id: this.dataId,
        isActive: this.isActive,
        age: this.age,
        first_name: this.firstName,
        last_name: this.lastName,
      });
      this.resetInputs();
    },
    resetInputs() {
      this.dataId = ''
      this.isActive = ''
      this.age = ''
      this.firstName = ''
      this.lastName = ''
    }
  }
});
.container {
  display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <button v-on:click="getData()">Get Data from API</button>
  <button v-on:click="resetData()">Reset Data</button>
  <div>
    <div>Id: <input v-model="dataId"/></div>
    <div>isActive: <input v-model="isActive" type="checkbox"/></div>
    <div>Age: <input v-model="age"/></div>
    <div>First Name: <input v-model="firstName"/></div>
    <div>Last Name: <input v-model="lastName"/></div>
    <div><button v-on:click="addCustomer()">Add Data</button></div>
  </div>
  <div class="container">
    <div class="column">
      <h3>mapState</h3>
      <div>Loading? {{isLoading}}</div>
      <ul>
        <li v-for="customer in customers">
          {{customer}}
        </li>
      </ul>
    </div>
    <div class="columns">
      <h3>magGetters</h3>
      <div>Loading? {{gIsLoading}}</div>
      <ul>
        <li v-for="customer in gCustomers">
          {{customer}}
        </li>
      </ul>
    </div>
  </div>
</div>

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

Having trouble with Vue.js single page application and sidebar/header alignment issue?

In the process of developing my Vue.js application, I have implemented a login screen followed by a left sidebar for navigation options such as dashboard, users, and settings. Additionally, there is a header section that provides features like signout and ...

What steps are needed to create a transport directly from the Console?

In my current setup, this is the code I have: const logger = new winston.Logger(); logger.add(winston.transports.Console, { level: environment === 'development' ? 'silly' : 'info', colorize: true, prettyPrint: true }); ...

How can I display data in jQuery FullCalendar without refreshing the page following an AJAX request?

I am currently working on integrating jQuery FullCalendar with PHP and MySQL. The issue I am facing is that when I insert a new event by selecting day(s) using AJAX, I am unsure how to display this newly added event without refreshing the page. Below is th ...

Rotating an animated object in ThreeJs: A simple guide

I have modeled a spaceship in Blender, added some random wobbling and rotation animations to it, and then exported the 3D model to ThreeJs. When the user presses the LEFT ARROW key, I want the spaceship to rotate to the left on the X-Y plane, and similarl ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

Tips on populating a text input field using ajax

This is the Jquery and ajax code I have written to load text box data sent from the server class. I am receiving a response, but for some reason, the data sent from the server is not loading into the textbox. You can see the error here. $(document).read ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. https://i.sstatic.net/8Yhaw.png The code snippet I have used is as follows: var db = require('./../routes/db'); ...

The removeEventListener method seems to be malfunctioning when used within an if statement in my three.js code

I am relatively new to JavaScript, although I have a background in mathematics which includes concepts like coordinate systems and trigonometry. I've been learning JavaScript through Codecademy for the past couple of weeks, and recently attempted to c ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

Error encountered in Next.js Webviewer during build process: "Reference Error - window is not defined"

Currently, I am in the process of developing a website that includes a PDF viewer within a dynamically imported page. When I run the code locally, everything works without any issues. However, when I execute the "npm run build" command, I encounter the fol ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

Combining two arrays under a unique condition in JavaScript

I am looking to group two arrays together. In case the second array does not have a code, then set it as an empty string (other questions and answers do not demonstrate how to do this). FIRST ARRAY: [ { code: "1", description: "one", ...

Hover over the sprites using the "spritely" plugin to see the magic unfold

I'm looking to initiate an animation when the mouse hovers over a sprite and have it stop when the mouse moves away. After exploring various solutions, I found one that seemed promising: Why does jQuery spritely animation play an extra frame on secon ...

The server is showing a discrepancy in date comparisons with MomentJS

I am struggling with grouping events by day in my application. While it works correctly in the development environment (Brazil), on the server (USA) the events that occur at the end of the day are being placed at the beginning of the next day. I suspect th ...

How to work with a JSON object in Internet Explorer 6

Looking for some quick answers that should be easy for someone with expertise to provide. I have a basic asp.net site that relies on JSON for various tasks (and JSON.stringify). Everything works fine in Firefox and the like, but in IE6 I'm getting a ...

Is Click and Mousemove available for iPhones?

I am experiencing some difficulties with mouseover and click events. While they work fine on desktop and laptop web browsers, they do not seem to function on the Safari browser of an iPhone. Below is the code snippet causing the issue: <script type="te ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Issue with the createActionThunk feature in redux toolkit

Hey there, I'm having an issue with my createAsyncThunk function. It seems to be working fine in manipulating the state by removing a value with a specific index, but for some reason, it's not updating the Firebase database. Also, when I try to a ...

Eliminate all elements marked with a particular class when the user clicks outside of a

I am currently building upon a project that I previously started here. Essentially, what I'm doing is dynamically generating tooltip popups that appear next to a link when it is clicked. However, I now need these tooltips to close when any click even ...