I don't think I understand how optional chaining affects the async/await functions.
I have a simple function that returns the user from Firebase Auth.
export async function getCurrentUser() {
const curUser = await projectAuth.currentUser?.getIdTokenResult();
return curUser || null;
With this code, if currentUser is null, curUser becomes undefined so I return null because react queryKey can not work with undefined results.
The problem is that, even when there is a logged in user, untill I manually click "refetch" in
ReactQueryDevTools, the data will not appear in cache and, therefore, will not appear in the UI.
In other words, on page reload, there is no user in cache untill I refetch the data.
Why is that?
When I don`t use optional chaining, I dont need to manually refetch to see the user in cache - I can see the returned curUser.
But in this case, without optional chaining, I have error:
Cannot read properties of null (reading 'getIdTokenResult')
Here is the react query hook:
export function useCurrentUser() {
const { isLoading, data: user } = useQuery({
queryKey: ["user"],
queryFn: getCurrentUser,
onError: (err) => console.log(err),
});
return { isLoading, user };
}
The reason why I know for sure that there is a logged in User is because when I try to get the user directly from the components, skipping the React Query step, I`m able to see the user.
So I'm not sure why I have to refetch the data manually with optional chaining or how to get rid of the type error if I dont user optional chaining.