1
votes

I am building a charts component that receives data from API according to dates that were picked by a date picker.

Handling dates and calling API are handled. The problem is when the data is large ( > 50 results) the next data comes inside object in next property. I am supposed to handle it from this returned next.

This is how the returned data looks like:

    average_satisfaction: 4.8307692307692305
    next: "nextURL"
    page_size: 50
    previous: null
    results: (50) [{…}, {…}]
    total_count: 130

I am thinking of a function that handles API and I just call it from useEffect but I am not sure how to make it check this next and then receive new data and push it

 const [results, setResults] = useState([]);

  useEffect(() => {
    if (startDate.length != 0) {
      handleAPIRequest(`someURL`).then((response) => console.log(response.data));
    }
  }, [startDate, endDate]);

  function handleAPIRequest(url) {
    return axios
      .get(url)
      .then((response) => {
        setResults(response.data.results);
        // here is where response.data.next has url of next 50 results
        return response;
      });
  }
1

1 Answers

1
votes

save all the results in the state instead of just the data.results.

  function handleAPIRequest(url) {
    return axios
      .get(url)
      .then((response) => {
        setResults(response.data);
        // here is where response.data.next has url of next 50 results
        return response;
      });
  }

in your render you can have a button like the following

return ( <button onClick={() => handleAPIRequest(response.data.next)}>Get Next</button> )

When you click the button, it will call your handleAPIRequest function, with the next url.

You can do similar with previous button.

Update - loop to get all results.

something like the following should work.

  function handleAPIRequest(url) {
    return axios
      .get(url)
      .then( async (response) => {

        let finalResults = response.data.results;
        if (response.data.next) {
           let moreResults = await handleAPIRequest(response.data.next);
           finalResults.concat(moreResults)
        }

        // here is where response.data.next has url of next 50 results
        return finalResults;
      });
  }