On start, I'm loading the data in useEffect like this:
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(12);
useEffect(() => {
const loadVehicles = async (dealershipId, id) => {
try {
const data = await getUserRequests(dealershipId, id, {
offset: (page - 1) * perPage,
limit: perPage,
});
setRequests(data.results);
} catch (err) {}
};
const loadUser = async (userId) => {
try {
const user = await getUserById(userId);
setSelectedUser(user);
} catch (err) {}
};
const loadData = async () => {
setIsLoading(true);
await loadVehicles(dealershipId, userId);
await loadUser(userId);
setIsLoading(false);
};
loadData();
}, [dealershipId, page, perPage, userId]);
Here, in the dependecy array I have "page" and "perPage", which are for pagination for vehicles. When I go to, for example, second page:
const changePageHandler = (pageNumber) => {
setPage(pageNumber);
};
page is updating, and then useEffect is calling. But the problem is that I just want to call loadVehicles() and not the loadUser() function.
And when I put loadVehicles(dealershipId, userId) function outside of the useEffect, and then call it after setPage(pageNumber), it's not getting the right page, because page is not updated yet.
How can I call only loadVehicles() with the correct page?
You should use another "useEffect" hook for handling page changes. Also it is better to define your functions outside your hooks so you can use them in other places as well.
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(12);
const loadVehicles = async (dealershipId, id) => {
try {
const data = await getUserRequests(dealershipId, id, {
offset: (page - 1) * perPage,
limit: perPage,
});
setRequests(data.results);
} catch (err) {}
};
const loadUser = async (userId) => {
try {
const user = await getUserById(userId);
setSelectedUser(user);
} catch (err) {}
};
const loadData = async () => {
setIsLoading(true);
await loadVehicles(dealershipId, userId);
await loadUser(userId);
setIsLoading(false);
};
useEffect(async() => {
await loadData();
}, [dealershipId, userId]);
useEffect(async() => {
setIsLoading(true);
await loadVehicles(dealershipId, userId);
setIsLoading(false);
}, [page, perPage]);
I am pretty sure you will understand the concept. The code above is just a hint.