Reputation: 11788
I have an api endpoint which gives an array of ingredients. Each ingredient has the following properties : id, name, measurementunit, density(kg/lt), cost/measurementunit. I have few thousands of ingredients and can keep increasing.
I am recieving a paginated api with variable page size from my backend server.
http://yoursite.com/api/ingredients?page=1&page_size=200
On client site how to organize my state shape w.r.t to page
and page_size
and ingredients
.
On client side i want to display only 15-20 items per page. So how to ensure that the items are displayed properly with pagination.
Similarly i have few more like ingredients. Eg: recipes, users and more.
Will redux able to handle such large data.
Upvotes: 0
Views: 3619
Reputation: 26054
Your ingredients response could be like this:
GET http://yoursite.com/api/ingredients?page=1&page_size=15
{
pages_count: 50,
page: 1,
ingredients: [
//first 15 ingredients
]
}
Your initial application state would be:
{
pages_count: 50,
page: 1,
page_size: 15,
ingredients: [
//first 15 ingredients
]
}
When user click Page 2
button (or Next Page
, or whatever), you dispatch an async action like this:
const changePage = (page) => (dispatch) => {
doGet(`http://yoursite.com/api/ingredients?page=${page}&page_size=15`)
.then(res => {
dispatch(retrieveIngredients(res.ingredients, page));
});
}
where retrieveIngredients
is an action creator:
const retrieveIngredients = (ingredients, page) => {
return {
type: 'retrieve_ingredients',
ingredients,
page
};
}
Then, the reducer that handles retrieve_ingredients
action updates its state to:
{
page: action.page,
ingredients: action.ingredients
}
In your IngredientsList
component (or something similar, I guess), you will just show the list state.ingredients
. Also, your PageSelector
will show from 1 to state.pages_count
page buttons.
Upvotes: 4