Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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"]
    }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

    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)
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!