DEV Community

Dev Master
Dev Master

Posted on

Best ways to update state array object using React Hooks?

I have

const [data, setData] = useState([{"name": "joy", "age": 25}, {"name": "tom", "age": 41}]);

Somehow I need to update only a particular object, May be name or age.

I am doing in such way. But It seems not good.

setData(prevState => {
      let obj = prevState.find(o => anycondition);
      if(obj !== undefined) {
        obj.name = "Demo";
      }
      return [...prevState];
    })

is there any other method to update only object from state array using React Hooks?

Top comments (1)

Collapse
 
malenalmendra profile image
Constanza Malen Almendra

Hi Dev Master, I don't know if there is another method to update an object in the array, but with this post, it helped me understand and solve a similar problem that I have.
So, Thanks <3