F
F
Funky_Rhyme2021-11-04 17:52:52
JavaScript
Funky_Rhyme, 2021-11-04 17:52:52

How to recursively accept json via API?

I am in the process of learning React. There is an API that returns a JSON file broken into pages, links to subsequent pages are in the JSON itself.
I'm trying to figure out how to recursively call a function followed by concatenation (or something similar) to get all the data at once. At the moment, it turns out to get either the first page or the last one.

const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async (url : string) => {
      const res = await fetch(url);
      const json = await res.json();
      if(json.pagination.links.next){
        /* Что-то мб тут надо написать */
      }
      setData(json.data);
    };
    fetchData("https://gorest.co.in/public/v1/users");
  }, [data]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-11-04
@Funky_Rhyme

Conditionally something like this:

useEffect(() => {
  const fetchData = async (url: string, data: any[] = []) => {
    const res = await fetch(url);
    const json = await res.json();
    if(json.pagination.links.next){
      await fetchData(json.pagination.links.next, data)
    }
    data.push(json.data);
    return data;
  };
  
  fetchData("https://gorest.co.in/public/v1/users").then(setData);
}, [url]);

data will be an array.
By the way, recursion is not required here:
useEffect(() => {
  const fetchData = async (url: string) => {
    let data: any[] = [];

    do {
      const res = await fetch(url);
      const json = await res.json();

      data.push(json.data);

      url = json.pagination.links.next;
    } while (url);

    return data;
  };

  fetchData("https://gorest.co.in/public/v1/users").then(setData);
}, [url]);

Well, instead any- you need to arrange your types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question