VUEX mutate array data each request

120

Question: VUEX mutate array data each request

I have some data from an API that I am storing in VUEX and then displaying in the UI. On initial page load there is a request that pulls in the initial data and displays. All works well. My issues is When I now submit a form input for another request using an event handler I am just pushing to the array and it is adding to the array (which makes sense) and creates another instance below the current data which I do not want. Is there a way to actually CHANGE / MUTATE the current data that is in the array and update the UI with the new values?

STORE

import { createStore } from 'vuex'; import axios from 'axios';      export default createStore({       state: {         ipData: [],         currentIP: '',       },       mutations: {         SET_CURRENT_IP(state, currentIP) {           state.currentIP = currentIP;         },         SET_IP_DATA(state, ipData) {           state.ipData.push(ipData);         },       },     }); 

FORM SUBMIT

 methods: {     async submitForm() {       const isFormValid = await this.v$.$validate();       if (!isFormValid) return;        axios         .get(`${this.url}${this.getIP}`, {           headers,         })         .then((response) => {           this.$store.commit('SET_IP_DATA', response.data);         })         .catch((error) => {           console.log(error.response);         });     },   }, 

VUEX OBJECT:

ipData:Array[1] 0:Object as:Object domains:Array[5] ip:"8.8.8.8" isp:"Google LLC" location:Object city:"Mountain View" country:"US" geonameId:5375480 lat:37.38605 lng:-122.08385 postalCode:"94035" region:"California" timezone:"-07:00" 

Total Answers: 1

50

Answers 1: of VUEX mutate array data each request

If your ipData is array of object, you can create another mutation for updating your array (use id or some other identifier to match right object):

UPDATE_IP_DATA(state, payload) {   state.ipData = [    ...state.ipData.map((item) =>       item.id !== payload.id         ? item         : {           ...item,           ...payload,         }      ),   ]; }