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

213
Views
Getting a list of items not only last list item gets rendered - React

I had a problem is that when I return some data from an API, add it to the state's array, I only get the last list item, even though it maps over more than 1 item.

const [items, setItems] = useState([]);
    
    const fetchData = ()=> {
          DataService.getEnergyDataList()
          .then(response => {
            response.data.map(res=>{
             setItems([...items, res.Voltage])
          });   
        }
        )
          .catch(e => {
            console.log(e);
          });
        
        }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The problem is that you're calling setItems repeatedly (in the map callback), reusing the original items and then supplying just one more. That sets up a bunch of state updates, only the last of which is kept.

Instead, use the array that map creates:¹

const fetchData = () => {
    DataService.getEnergyDataList()
    .then(response => {
        setItems([...items, ...response.data.map(res => res.Voltage)]);
    })
    .catch(e => {
        console.log(e);
    });
};

¹ Any time you find yourself writing map without using the array that map creates, it's incorrect. (More on my blog.) Figure out whether you need that array and either modify the code to use the array map returns, or change the map to some other looping mechanism.

about 4 years ago · Juan Pablo Isaza Report

0

The problem is you are setting item for each element in .map callback. If you want to append the new response to items, you can use the callback approach of setState, something like:

.then(response => 
     setItems(currentItems => [...currentItems, ...response.data.map(res=> res.votage))
    );

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!