I have a NextJS project that uses NextAuth for session management and then React Query to retrieve data on the front-end.
However, with the current format (as seen below), useSession() will return undefined
while it checks if the session is authenticated, and then this undefined
is used in the reactQuery, which will itself return undefined
. How can I make sure useQuery is only called after the session is successfully retrieved and includes the userID, which can then be passed to useQuery?
const AirdropsPage = () => {
const { data: session } = useSession();
const { isLoading, isError, data } = useQuery(["airdropsData"], () =>
fetch(`/api/airdrops?id=${session?.user?.id}`).then((res) => res.json()) //id is undefined
);
return (
{isLoading ? (
<Loader />
) : data ? (
<Table data={data.airdrops} columns={columns} />
) : null}
);
};
Generally, what you'd want is to add all things that you use in your queryFn as the queryKey. Then, you can disable the query when your dependencies are not ready yet:
const { data: session } = useSession();
const id = session?.user?.id
const { isLoading, isError, data } = useQuery(
["airdropsData", id],
() =>
fetch(`/api/airdrops?id=${id}`).then((res) => res.json())
),
{
enabled: !!id
}
)
as soon as useSession
returns the id, the query will enable and will start to fetch. This is documented here.