I understand that calls to useState functions are asynchronous, but I'm having an issue with a click event and a subsequent function call where my state is not updating as needed.
Currently, I fire an onClick event for three buttons(first, next, last). Based on which is clicked - I want to update the state of my useState hook that controls the current active page:
const [page, setPage] = useState(0);
Here is the onClick event:
const firstNextLast = (event) => {
if (event.target.name === 'first' && page !== 0) {
setPage((prevPage) => 0);
} else if (event.target.name === 'next' && page !== totalPages) {
setPage((prevPage) => prevPage + 1);
} else if (event.target.name === 'last') {
setPage((prevPage) => totalPages);
}
fetchFirstNextLast();
};
Here is the function fetchFirstNextLast():
const fetchFirstNextLast = () => {
const params = {
area: uriEncodeGJ.current,
page,
size: pageSize,
};
getEGMModelsWithin(gravitationalModel[0], params)
.then((data) => {
setGridData(data);
setSuccess(true);
setPage(data.data.pageNumber);
setPageSize(data.data.pageSize);
updateLat(data);
})
.catch((err) => {
setGridData(err);
setSuccess(false);
});
};
The issue with this is that the value for page
isn't updated when I call fetchFirstNextLast(); I even attempted passing in fetchFirstNextLast() in as a callback to setPage() like so:
const firstNextLast = (event) => {
if (event.target.name === 'first' && page !== 0) {
setPage((prevPage) => 0, fetchFirstNextLast());
} else if (event.target.name === 'next' && page !== totalPages) {
setPage((prevPage) => prevPage + 1, fetchFirstNextLast());
} else if (event.target.name === 'last') {
setPage((prevPage) => totalPages, fetchFirstNextLast());
}
};
None of these attempts have worked. Also, I checked to see if I'm using setPage() to return the state back to 0 anywhere else in the program, so it's a not a bug of that sort. Admonishment would be greatly appreciated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…