Home > Software design >  Can't change a specific element from a array of objects
Can't change a specific element from a array of objects

Time:10-11

I have a function that changes the name of the user checking it on a array of objects. The code:

for (var i = 0; i < state.users.length; i  ){
      if (state.users[i].id == id) {
        state.users[i].email = change;
        console.log(state.users[i].email)
      }
    }

The value of state.users[i] does not get any change with "=". How can I change it?

The state code:

  state: {
    users: [
    {id: 1, name : "test", password : "test" , email : '[email protected]', admin : false},
    {id: 2, name : "Pol", password: "PolProva", email : '[email protected]', admin : true},
    {id: 3, name : "Marta", password : "MartaProva", email : '[email protected]', admin : true}
    ],
    userLogged : false
  },

How i do get it:

import {f7, useStore } from 'framework7-vue';
import localforage from 'localforage'; 

    export default {
        setup(){
            const users = useStore('getUsers');
            /*const editGeneral = (id, change, toChange) => f7.store.dispatch('editName', {id : id, change : change, toChange : toChange}); */
            const testChange = (id, change) => f7.store.dispatch('testChange', {id : id, change : change})
            return{
                users,
                /*editGeneral,*/
                testChange
            };
        },
     }

CodePudding user response:

The state is immutable, so you can't change direct like that. If you are using React, use setState or useState hook to update it. Else, use destructuring to update it.

CodePudding user response:

aftere update return it.

let state = {
  users: [{
      id: 1,
      name: "test",
      password: "test",
      email: '[email protected]',
      admin: false
    },
    {
      id: 2,
      name: "Pol",
      password: "PolProva",
      email: '[email protected]',
      admin: true
    },
    {
      id: 3,
      name: "Marta",
      password: "MartaProva",
      email: '[email protected]',
      admin: true
    }
  ],
  userLogged: false
}

let myId = 3
let myKey = 'email'
let myValue = '[email protected]'

let data = state.users.map((obj) => {
  if (obj.id == myId) {
    obj[myKey] = myValue
  }
  return obj
})
console.log(data)

  • Related