Vuex store updating all instances, I only want current instance updated
That is because you're incrementing the likes for all comments regardless of their IDs. In order to increment the link for a specific comment, you need to pass some kind of identifier that will identify your comment. That identifier should be unique: in this case let's assume that the id
field is unique.
Then, in your component you will need to commit the mutation with this bit of information (the identifier):
<button @click="addLike(comment.id)">
<img src="/img/icon-plus.svg" />
</button>
<p class="py-3 text-primaryBlue">{{ comment.likes }}</p>
<button @click="subtractLike(comment.id)">
<img src="/img/icon-minus.svg" />
</button>
<script>
export default {
data() {
return {
reply: false,
}
},
},
methods: {
addLike(id) {
this.$store.commit('comments/addLikes', id)
},
subtractLike(id) {
this.$store.commit('comments/subtractLikes', id)
},
},
}
</script>
Then you will need to update your commit definition to include that identifier. Use that identifier to find the comment whose like
property you want to increment/decrement:
addLikes(state, id) {
const foundComment = state.comments.find(comment => comment.id === id);
if (foundComment) foundCommment.likes++;
},
subtractLikes(state, id) {
const foundComment = state.comments.find(comment => comment.id === id);
if (foundComment) foundCommment.likes--;
},
p/s: Remember that objects in your array is by reference, so foundComment
is simply a reference to the original comment object in state.comments
, which allows you to mutate it directly.