I am trying to get a grip on Vuex by developing a small Games List app with a small NodeJS backend.
I have a Game List component with an option to update a game's completed status with a button
<template>
<div id="gameList">
<div v-for="game in allGames" :key="game._id" class="game">
<strong>{{ game.name }}</strong>
<em class="completed">{{ game.completed }}</em>
<button @click="updateCompleted(game._id)" v-if="game.completed === false">Set completed</button>
</div>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "GameList",
methods: {
...mapActions(["getGames", "updateCompleted"])
},
computed: mapGetters(["allGames"]),
created() {
this.getGames();
}
};
</script>
And my Store
const state = {
gamelist: []
};
const getters = {
allGames: state => state.gamelist
};
const actions = {
getGames: async context => {
const response = await axios.get("http://localhost:8081/allgames");
context.commit("setGames", response.data);
},
updateCompleted: async (context, payload) => {
const response = await axios.put(
`http://localhost:8081/update/${payload}`, {
completed: true
}
);
context.commit('updateCompleted', response)
}
};
const mutations = {
setGames: (state, payload) => (state.gamelist = payload),
updateCompleted: state => console.log(state)
};
export default {
state,
getters,
actions,
mutations
};
The getter works perfectly and so does the action, but I can't seem to figure out how to mutate the state ( the gamelist ) after the PUT response so that I can update the view and display the game's new completed status without doing a refresh. The PUT response is just a "success" message, when the game in the database has been updated.
The GET response in the getGames action looks like this:
[{"completed":true,"_id":"5e0df1af63680526c07c670c","name":"Alien Isolation"},{"completed":false,"_id":"5e0df75ea252fe27e58577f6","name":"Red Dead Redemption"}]
Change these as follows:
context.commit('updateCompleted', {response, payload});
updateCompleted: (state, data) => {
if(data.response.status === 200){
let game = state.gamelist.findIndex(game => game._id === data.payload);
state.gamelist[game].completed = true;
}
}