Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Object in Array dynamically in React state

I'm fairly new to ReactJS and wrote this function I want to use to update an object in my state. It seems unable to use the "name" param to update my object and I don't really get why. I tried 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 browser console, but it doesn't update my state either. Any idea would be appreciated. I spent 2 hours on google but didn't find anything.

like image 926
timo.js Avatar asked Mar 03 '26 12:03

timo.js


2 Answers

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));
like image 170
nem0z Avatar answered Mar 05 '26 01:03

nem0z


const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
if (obj.id === id) {
return { obj[name]= newValue};
}
return obj;
});
setSelected({...newState});
}
like image 44
sohan724code Avatar answered Mar 05 '26 01:03

sohan724code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!