I'm trying to fetch a url when the page first loads and when the location changes. The first load works fine. The record id is pulled from params and when that changes, useEffect gets called again to reset state and reload the new records. However, all of the set* calls in useEffect aren't doing anything as the loadData() method sees the old data still (hasMoreData=false, dataRecords=[...]).
export function MyComponent(props) {
const [hasMoreData, setHasMoreData] = useState(true);
const [dataRecords, setDataRecords] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const params = useParams();
const location = useLocation();
const { id } = params;
const loadData = useCallback((page = 1) => {
if (hasMoreData) {
fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
const { data } = response;
// note: pagination logic omitted for clarity
if (data && data.length > 0) {
setDataRecords(data);
} else {
setHasMoreData(false);
}
});
}
}, [id, dataRecords, hasMoreData]);
useEffect(() => {
// id param has changed, or its the first load - reset all fields, then fetch new data
setHasMoreData(true);
setDataRecords([]);
setCurrentPage(1);
loadData(currentPage);
}, [location]);
// ...currentPage managed via infiniteScroll
};
What am I doing wrong here?
Comments on the original question lead me to a better way to achieve what I was after. I needed to detect a location change, pagination changes and loading data on initial page load and useCallback wasn't the best way to go about this because the state changes are asynchronous and it didn't see the new values yet. Instead I used a separate useEffect() for changes to the location so I can reset the internal state data, and a second useEffect() to handle changes to currentPage rather than calling loadData() directly.
export function MyComponent(props) {
const [hasMoreData, setHasMoreData] = useState(true);
const [dataRecords, setDataRecords] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const params = useParams();
const location = useLocation();
const { id } = params;
useEffect(() => {
// location changed, reset all data
setHasMoreData(true);
setDataRecords([]);
setCurrentPage(1);
}, [location]);
useEffect(() => {
// id param has changed, or its the first load - reset all fields, then fetch new data
loadData(currentPage);
function loadData(page = 1) {
if (hasMoreData) {
fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
const { data } = response;
// note: pagination logic omitted for clarity
if (data && data.length > 0) {
setDataRecords(data);
} else {
setHasMoreData(false);
}
});
}
}
}, [currentPage]);
// ...currentPage managed via infiniteScroll
};