Home > other >  How to update Object in Array dynamically in React state
How to update Object in Array dynamically in React state

Time:08-04

I'm fairly new to ReactJS and I wrote this function I want to use to update a object in my state. It seems not to be able to use the "name" param to update my object and I don't really get why. I tryd to code it in template literals as well.

const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
  if (obj.id === id) {
    return { ...obj, name: newValue };
  }
  return obj;
});
setSelected(newState);

};

I get no error in the browserconsole, but it doesn't update my state either. Any ideas would be appreciated I spend 2 hours on google but didn't find anything

CodePudding user response:

When you call obj.property = 'aaa' you set property to aaa. What you try to do is update the property contained by the variable name, what you code does is update the property name.

To update a property from a variable you need to use :

const property = 'name'
obj[property] = 'aaa'

equivalente to :

obj.name == 'aaa'

This code solves your probleme :

const handleAccountingChange = (newValue, name, id) => {
    // For the exemple I declare selected here
    const selected = [ {id: 1, test: 'aaa'}, {id: 2, test: 'bbb'} ];
    
    const newState = selected.map((obj) => {
        if (obj.id === id) {
            let myObj = {...obj};
            myObj[name] = newValue;
            return myObj;
        }
        return obj;
    });

    return newState; // instead ou can use setSelected(newState)
};



console.log(handleAccountingChange('ccc', 'test', 1));

CodePudding user response:

const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
if (obj.id === id) {
return { obj[name]= newValue};
}
return obj;
});
setSelected({...newState});
}
  • Related