Currently, I am developing an application in Vue that utilizes Vuex for state management.
For CRUD operations on the data, I have implemented Axios.
The issue arises when, for example...
I make a POST request to my MongoDB database through an Express server.
Even though both are temporary placeholders which will be replaced later, the state in Vuex does not update and the component fails to auto rerender with the new data. A page refresh becomes necessary.
While I can manually re-render a component using mutations on the state as shown in the example below, this approach is not ideal or preferred by me.
Is there a way to prompt updates to the state to automatically trigger a rerender of the component when performing post/delete/update actions? I am not interested in hard refreshes or placing fetchData() inside the updated() lifecycle hook, since the component is constantly polling for fresh data every 100ms.
The code snippet below is not mine, but it perfectly illustrates what I am aiming for:
// Tasks module
import axios from 'axios';
const resource_uri = "http://localhost:3000/task/";
const state = {
tasks: []
};
const getters = {
allTasks: state => state.tasks
};
const actions = {
async fetchTasks({ commit }) {
const response = await axios.get(resource_uri);
commit('setTasks', response.data);
},
async addTask( { commit }, task) {
const response = await axios.post(resource_uri, task);
commit('newTask', response.data);
},
async updateTask( { commit }, task) {
const response = await axios.put(`${resource_uri}${task.id}`, task);
commit('updTask', response.data);
},
async removeTask( { commit }, task) {
const response = await axios.delete(`${resource_uri}${task.id}`);
commit('deleteTask', task);
}
};
const mutations = {
setTasks: (state, tasks) => state.tasks = tasks,
newTask: (state, task) => state.tasks.unshift(task),
updTask: (state, updatedTask) => {
const index = state.tasks.findIndex(t => t.id === updatedTask.id);
if(index !== -1) {
state.tasks.splice(index, 1, updatedTask);
}
},
deleteTask: (state, task) => state.tasks = state.tasks.filter(t => task.id !== t.id),
};
export default {
state, getters, actions, mutations
}
Edit: Current workflow looks like this:
- axios.get(task)
- Commit and save data in
state.tasks[]
- When
axios.post(data)
is called, the server receives the data but thestate.tasks[]
remains unchanged, causing the component to not re-render with the new data.
How can I trigger a component re-render when data has been saved in the database without directly modifying state.tasks[]
using array methods?