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

140
Views
Is this the wrong way of handling array of objects from api call?

I am trying to store a array of names from a json response containing an array of objects.

For some reason the printing array will have nothing inside.Is this the correct way of doing it. Its not working for some reason otherwise no errors.

also the forEach is loop not even running once i tested it.


useEffect(() => {
  
    instance.get('/')
    .then(function (response) {
      // handle success
      //console.log(response);
      console.log(response.data);
      (response.data).forEach(newValue=>
        {
          setArray(oldArray => [...oldArray,newValue.name])
        }
      )
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      console.log("printing array 1",Array);
      // always executed
    });
    
    if(Array)
    console.log("printing array 2",Array);
    
  },[]);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this:

setArray([...oldArray, ...response.data?.map(item=>item.name)]);

Rather than updating your state for every item in the new array, just get all the name props as an array from the new array using map and then use the spread operator to combine both new and old arrays.

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!