-1

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);
          });
        
        }
  • 1
    You're mapping over the response which contains just one item so it's only rendering one item. `const i = [...items, response.data.Voltage]; setItems(i);` – Michael Hallabrin Jan 17 '22 at 14:19

2 Answers2

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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))
    );