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?