skip to Main Content

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


  1. 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 that top10 doesn’t change after each iteration (it only changes on the next rerender), so you’re not accumulating your top10 state.

    An alternative is to use .slice() to set your new state, assuming that top10 stats off an an empty array/nothing:

    .then(response => {
      setTop10(response.results.rankings.slice(0, 10));
    })
    

    If you want to continue using a loop, then you can create a new array, push to that, and then set your state

    .then(response => {
      const newState = [];
      for(var i = 0; i < 10; i++) {
        newState.push(response.results.rankings[i]);
      }
      setTop10(newState);
    });
    

    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.

    Login or Signup to reply.
  2.         .then(response => {
                for(let i=0;i<10;i++){
                    setTop10([...top10, response.results.rankings[i]])
                }
            })
    

    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 ?

            .then(response => {
                setTop10(response.results.rankings.slice(0,10))
            })
    
    
    Login or Signup to reply.
  3. Make sure top10 is array.
    Example :

    (const [top10, setTop10] = useState([]);
    

    Then use arrow to mention current array and new data.

    for(let i=0;i<10;i++){
        setTop10(top10 => [...top10, response.results.rankings[i]])
    }
    
    Login or Signup to reply.
  4. You can use slice method to extract the first 10 object from API response array

     useEffect(()=>{
            fetch('https://tennis-live-data.p.rapidapi.com/rankings/ATP', options)
                .then(response => response.json())
                .then(response => {
                    const topTen = response.results.rankings.slice(0, 10);
                  
                })
                .catch(err => console.error(err))},[]);
    enter code here
    

    to print all 10 objects use foreach loop hope it helps

    top10.forEach((item, index) => {
      console.log(`Item ${index + 1}: `, item);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search