reactjsuse-statearrayobject

Modify useState array of object


I have a useState array of object as:

const [processes, setProcesses] = useState([]);

After fetching values from db it becomes:

[{processId: 0, status: "true"},
{processId: 1, status: "true"}]

Now I want to add new property to it so that it becomes like:

[{processId: 0, name:"process1",status: "true",active:"true"},
{processId: 1, name:"process2",status: "true",active:"true"}]

where the name is coming from:

var allProcNames=["process1","process2"]

I've tried the below:

var objProc = JSON.parse(JSON.stringify(processes));

objProc.map((proc) => ({
        ...proc,
        name: procNames[proc.processId],
        active: true,
    }));

However it is logging the same only:

[{processId: 0, status: "true"}]

What can be done apart from adding a new column to db for the process name?


Solution

  • You shouldn't try to mutate the state directly. (Check ref: https://reactjs.org/docs/react-component.html#setstate)

    You could use filter or map methods and update your current state with a whole new state:

    const [processes, setProcesses] = useState([
    {processId: 0, status: "true"},
    {processId: 1, status: "true"}
    ]);
    
    const arrayObjUpdater = () => {
      const newArrayState = processes.map((currentProcess, idx) => ({
              ...currentProcess,
              name: `proccess${idx}`,
              active: "true"
      }));
      console.log(newArrayState); // See output below
    
      return setProcesses(newArrayState);
    }
    
    arrayObjUpdater();
    // Output: [{processId: 0, name:"process1",status: "true",active:"true"}, {processId: 1, name:"process2",status: "true",active:"true"}]