How to implement React pagination frontend with DynamoDB backend

1.5k Views Asked by At

I have successfully implemented DynamoDB pagination and tested with API Gateway and Postman. However, I'm confused on how to implement pagination in React frontend.

Currently, upon first call to backend api, it limits to return 2 images, with LastEvaluatedKey. In my React, I implemented React.useEffect() as:

React.useEffect(() => {
    async function getAllImages() {
        const result = await getImages(auth.getIdToken()); 
        setImages(result.items); 
    }
    try {
        getAllImages(); 
    } catch(e) {
        alert(`Failed to fetch images ${e.message}`); 
    }
}, [auth]); 

In my api, I implement function to call backend:

export async function getImages(idToken: string): Promise<any> {
const response = await axios.get(`${apiEndpoint}/images`, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${idToken}`
    }
}); 

let nextKey = response.data.nextKey;

if (response.data.nextKey === null) {
    console.log('No more pictures to load!');
    return
} else {
    const moreResponse = await axios.get(`${apiEndpoint}/images?nextKey=${nextKey}`, {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${idToken}`
        }
    }); 
}

// return response.data.items;
return response.data;

}

Then, I create a "Load More" button to load more images. But I get lost at how to call second call to backend with LastEvaluatedKey to load more images?

This is my More button

Here is my github project: https://github.com/ploratran/DogLookBook/tree/master/client

1

There are 1 best solutions below

5
On

Pagination can be done only if we have a marker. In case of UI application, it can be hard, anti-pattern to keep store of last-evaluated-key. But, you need to keep track of some information which DDB needs in order to know from where to start.

My recommendation will be to do the following -

  1. Keep track of your Nth record received from UI, ie, whatever last record is fetched till now.
  2. When request for next page is called, make a call to DDB with Nth record as of now and get the marker from this query.
  3. Pass the last-evaluated-key found in step 2, to your paginated query to return next set of elements.
  4. Update the Nth record.
  5. Repeat steps 2-4.