Im using react functional components.
To call data from an api , there are available filters and pagination. When I change a filter type, the pagination has to return to the first page.
const pageChange = (page) => {
setPage(page);
};
useEffect(() => {
async function fetchData() {
const dateFilter = start && end ? `start=${start}&end=${end}` : null;
const pageFilter = `offset=${
(page - 1) * ITEMS_PER_PAGE
}&limit=${ITEMS_PER_PAGE}`;
const defaultFilters = `${dateFilter?dateFilter:''}${dateFilter?'&':''}${pageFilter}`;
let request = null;
switch (type) {
case "upcoming":
request = fetchUpcomingLaunches(defaultFilters);
break;
case "successful":
request = fetchLaunches(`${defaultFilters}&launch_success=true`);
break;
case "failed":
request = fetchLaunches(`${defaultFilters}&launch_success=false`);
break;
default:
request = fetchLaunches(defaultFilters);
break;
}
try {
setIsLoading(true);
const response = await request;
setItems(getItems(response.data));
setIsLoading(false);
} catch (err) {
setIsLoading(false);
}
}
fetchData();
}, [start, end, type, page]);
Im using material ui pagination :
<Pagination
count={20}
variant="outlined"
shape="rounded"
size="large"
page={page}
onChange={(event, val) => pageChange(val)}
/>
Here the start, end and type are filters . If any of there filters changes, the api has to be called and the data should be refreshed. The api has to return the paginated response based on the page . My problem is that when any of the other filters are changed , the page should reset to the first page and data should be loaded from the first page. Is it possible to use two useEffect hooks? I have tried useEffect with type, start, end dependecies . As of now the api is getting called two times as setPage is called again.