Search code examples
reactjschildrenuse-state

How to change data of children with useState?


const [blocks, setBlocks] = useState({
   "time": null,
   "blocks": [
      {
         "key": 1,
         "data": "This is some data"
      }
   ]
});

How can I use setBlocks to change "data" to "this is some other data"?


Solution

  • set method of useState not only accepts data, but also accepts functions.

    setState(prevState => {
      return {...prevState, ...updatedValues};
    });
    

    So you can write something like this.

    setBlocks(prevState => ({
      ...prevState,
      blocks: prevState.blocks.map(v => {
        return (v.key === 1)
          ? {...v, data: 'this is some other data'}
          : v;
      }),
    });