Answer the question
In order to leave comments, you need to log in
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
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]);
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]);
any
- you need to arrange your types.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question