简体   繁体   中英

How to update an array inside an array of objects with useState function component

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"]
    }
]
    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)
setTask((oldTasks) => {
  const myTask = oldTasks.find(t => t.task_id === 123)
  return [
    ...oldTasks.filter(ot => ot.task_id != 123),
    {
      ...myTask,
      photos: [...myTask.photos, new_photo],
    }
  ]
})


Ref: spread operator and asynchronous state update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM