How to chain Graphql queries

Hi, i need to get more than 20 Graphql entries at first pageload. i understand that i can query again with the cursor. but i don't understand how to chain those queries automatically.
Now i get the first 20 results like so:

React.useEffect(() => {
    client.query({
      query: GETDATA
    }).then(response => {
        setDocData(doc=>[...doc,response.data.allItems.edges]);
    }).catch(error => {
      console.error(error);
    });
    },[])

i think i should somehow chain another .then() but i don't understand how i can chain as much thens as i need to get all of the documents and add it to my doc data…

thanks!

i tried somehow like this:

React.useEffect(() => {
client.query({
	query: GETDATA
}).then(response => {
	console.log(response);
	setDocData(response.data.allItems.edges);
	if(response.data.allItems.pageInfo.hasNextPage){
		console.log("has!!")
		client.query({
			query: GETNEXTDATA,variables:{after:response.data.allItems.pageInfo.endCursor}
		}).then(response => {
			console.log(response);
			setDocData(doc=>[...doc,response.data.allItems.edges]);
		})
	}
}).catch(error => {
	console.error(error);
});
},[doc])

but i have two problems with that:

  1. i want to do the second query as often as allItems.pageInfo.hasNextPage will be true. how to chain the queries as long as this will be true and not hardcode a chain?

  2. i have a invinite loop when i try to append the new data to the docdata state:
    setDocData(doc=>[…doc,response.data.allItems.edges])
    So, how can i update this state only as long as there is additional data?

Hi Michael,

Welcome to Prismic community, You can use recursion instead to fetch all the data and you break the recursion when hasNextPage is false.

Fares

hi fares, thanks a lot for your reply! thats sounds cool but i am very new to promises, graphql and react. so i have no idea how to design this thing recursive. maybe you know of a tutorial or you can sketch out a very basic pattern design? i think, i just need a startingpoint to figure out the rest by myself…

i think, i have a solution. at least it seems to work for now.

 let fq = (res) => client.query({
  		query: GETNEXTDATA,variables:{after:res.data.allItems.pageInfo.endCursor}
	}).then(response => {
		collectedData=[...collectedData,...response.data.allItems.edges]
        console.log("combined data",collectedData)

		if(response.data.allItems.pageInfo.hasNextPage){
        	return fq(response)

    	}else{
    		// use State here to set data, then resolve
    		 setDocData(collectedData);
        	return Promise.resolve();
   		}
	})