Home > Software design >  How to update an array inside an array of objects with useState function component
How to update an array inside an array of objects with useState function component

Time:03-14

How to update array inside array use state function component the array is inside the setTask() and how to use setTask() and add new_photo in photos

const new_photo = "testing2.png"; <------------ insert this value in photos

const [task, setTask] = useState([
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png"] <------------ here
    }
])

Result should be like this:

[
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png","testing2.png"]
    }
]

CodePudding user response:

setTask((oldTasks) => {
  const myTask = oldTasks.find(t => t.task_id === 123)
  return [
    ...oldTasks,
    {
      ...myTask,
      photos: [...myTask.photos, new_photo],
    }
  ]
})


Ref: spread operator and asynchronous state update

CodePudding user response:

    const new_photo = "testing2.png"; // <------------ insert this value in photos

const [task, setTask] = useState([
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png"] // <------------ here
    }
])

const arrayPush = (ID) => {
  setTask((element) => {
    element.forEach((e) => {
      if (e.task_id === ID) {
       e.photos.push(new_photo);
     }
    });
  });
console.log(task);
}

const arrayPush2 = (ID) => {
    let taskCopy = Array.from(task)
    taskCopy.forEach((element) => {
      if (element.task_id === ID) {
        element.photos.push(new_photo);
      }
    });
    setTask(taskCopy)
};

arrayPush(123)
arrayPush2(123)
  • Related