ReactJS - Update state (Complex state) having array values

Normally, state of ReactJS component may have many state properties/constants/variables to hold values after something is done. If state object has one value, than is very easy to update this value using setXXX function. But if the state has Array type values, than you need to merge the values. To merge the values, you need to pull previous values, extract them and create new array using the old values and new value. Then set the new update array back to state.

Suppose following is the state fileInfos which contains array of file information objects. Initially, you just add blank array.

const [fileInfos, setFileInfos] = useState([]);

Now, following is the code which updates value in the above state of array objects.

 setFileInfos((preFileInfos)=>{
         return [...preFileInfos,{idx:idx,file:file,url:response.data.url,thumbUrl:response.data.thumbUrl}]
  });

Here, Response the object having further some properties. You can use anything, its just example.

Tags