hey guys I have an api call that returns an array of 250 objects but I only want the first 10 objects stored in my array
useEffect(()=>{
fetch('https://tennis-live-data.p.rapidapi.com/rankings/ATP', options)
.then(response => response.json())
.then(response => {
for(let i=0;i<10;i++){
setTop10([...top10, response.results.rankings[i]])
}
})
.catch(err => console.error(err))},[])
I tried doing this but it is not working, it’s only adding the 10th object
4
Answers
Generally you shouldn’t use state setter functions (such as
setTop10
) in a loop. You should firstly create your array of data that you want to set, and then set your state. At the moment, your issue is thattop10
doesn’t change after each iteration (it only changes on the next rerender), so you’re not accumulating yourtop10
state.An alternative is to use
.slice()
to set your new state, assuming thattop10
stats off an an empty array/nothing:If you want to continue using a loop, then you can create a new array, push to that, and then set your state
Also consider if it is possible to change your API call to only give you the data that you need on the client side, and instead request for only 10 items in your API call if it allows for it.
I guess, this code is setting value to top10.
setTop10 function will set top10 with value of old top10, and add response.results.rankings[i] is what you want.
how about ?
Make sure top10 is array.
Example :
You can use slice method to extract the first 10 object from API response array
to print all 10 objects use foreach loop hope it helps