Deepa
Deepa

Reputation: 151

Loop through nested axios get request - pagination api response

I want to loop through my api repsonse which has an pagination.

Here is my api response

{
    count: 165,
    next: "http://example.com/name?offset=30&per_page=30",
    previous: null
}

Here is my useEffect

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

async function getAllData() {
    await axios.get("/names").then((response) => { // what should be the logic here to loop the api response
        setData(response.data.results);
    }).catch((error) => {
        console.log(error);
    });
}

How should be the implementation of this ?

Thank you

Upvotes: 0

Views: 701

Answers (1)

User81646
User81646

Reputation: 743

This code will make the inital request and will keep requesting the "next" endpoint provided by the API until it is no longer there, meaning that you have parsed all the data.

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

async function requestData()
{
    let nextUrl = "/names";
  
    do {
        const response = await axios.get(nextUrl);
        nextUrl = response.data.next;
    
        setData([...data, ...response.data.results]);
    
    } while(nextUrl != null)
}

Upvotes: 2

Related Questions