I'm trying to add a Date object as a react-query variable, however whenever I use a dynamic date, instead of a static value it calls the query infinitely, instead of just once. I'm not sure of best way to break this loop or to refactor the code so that it will run only once. Can anyone see what I am doing doing wrong?
To be clear, the infinite loop happens when I replace "2022-04-20T23:40:09.038Z" with the 'today' const.
const MoviesPage = () => {
const [activeTab, setActiveTab] = useState<TabType | undefined>(tabs?.[0]);
const [noOfColumns, setNoOfColumns] = useState(0);
const [{ page, titles }, setState] = useState<State>(DEFAULT_STATE);
const handleTabClick = (tab: TabType) => {
setState({ page: 0, titles: [] });
setActiveTab(tab);
};
const today = dayjs().toISOString();
const { data, isFetching } = useMoviesQuery(gqlClient, {
page: page,
limit: 16,
afterDate: activeTab?.name === "coming-soon" && "2022-04-20T23:40:09.038Z",
});
useEffect(() => {
if (isFetching) {
return;
}
if (data) {
setState((v) => {
return {
...v,
titles: [...v.titles, ...data.movies],
page: page,
};
});
}
}, [data, isFetching, setState, page]);
Not really sure what useMoviesQuery is doing, but i would change it to the following. Passing in objects like data for example without accessing a property are prone to cause infinite loops(this is entirely based on my experience).
My assumption is that useMoviesQuery is constantly being ran based on a onChange event maybe ? therefore data is constantly being updated triggering the useEffect. Passing in just isFetching should be suffice enough to get the latest updates from data. That is, if isFetching is being updated as well. It's possibly being set from true to false within milliseconds based on the onChangeEvent or however this query is being trigged.
const MoviesPage = () => {
const [activeTab, setActiveTab] = useState<TabType | undefined>(tabs?.[0]);
const [noOfColumns, setNoOfColumns] = useState(0);
const [{ page, titles }, setState] = useState<State>(DEFAULT_STATE);
const handleTabClick = (tab: TabType) => {
setState({ page: 0, titles: [] });
setActiveTab(tab);
};
const today = dayjs().toISOString();
const { data, isFetching } = useMoviesQuery(gqlClient, {
page: page,
limit: 16,
afterDate: activeTab?.name === "coming-soon" && "2022-04-20T23:40:09.038Z",
});
useEffect(() => {
if (isFetching) {
return;
}
if (!isFetching && data) {
setState((v) => {
return {
...v,
titles: [...v.titles, ...data.movies],
page: page,
};
});
}
}, [isFetching])