M
M
MeMoJlor2021-09-24 13:18:33
Vue.js
MeMoJlor, 2021-09-24 13:18:33

Why is the value not changing in Vuex?

There is a list with buttons. By clicking on the button, a mutation is called, in which the id is passed. The boolean property cheked is taken from the element with the specified id, and its value is inverted, but nothing changes in the state. As I understand it, because the method only returns false/true, not the modified item. How to correctly implement the method in this situation?

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    posts: [
      {txt: '123', cheked: false, id: 40934564356},
      {txt: '321', cheked: true, id: 23546345656},
      {txt: '132', cheked: false, id: 35645645345},
    ]
  },
  mutations: {
    chekedItem(state, id) {
      return state.posts.filter(item => item.id == id)
      .map(item => item.cheked = !item.cheked);
    }
  },
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-09-24
@MeMoJlor

Shit code of course, but what you showed is working. The problem is somewhere else - maybe the mutation is not called, or you are passing a non-existent id when calling.

By clicking on the button, a mutation is called, in which the id is passed.

These words should be illustrated with a code.
As I understand it, because the method only returns false/true, not the modified item.

Do not understand. Did you try to open the vuex documentation, or did you pull some bits of code from a YouTube video?
How should your code look like ? Look, compare with what you really have.

R
Rsa97, 2021-09-24
@Rsa97

Mutations are synchronous methods that directly change the value of properties. Nothing changes for you, because .map creates a new array that is not written anywhere.

mutations: {
  TOGGLE_ITEM: (state, id) => {
    const item = state.posts.find((item) => item.id === id);
    if (item !== undefined) {
      item.checked = !item.checked;
    }
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question