T
TanStack3y ago
other-emerald

Run a function only once for all instances

Hello, I'm in an interesting predicament. I have a hook that looks something like this:
export function useUser() {
const navigate = useNavigate();
const query = useQuery({
queryKey: ['auth', 'useUser'],
queryFn: async () => {
// do some stuff and either return { user: data } || { user: null }
},
suspense: true,
});

useEffect(() => {
supabaseClient.auth.onAuthStateChange(async () => {
await query.refetch();
navigate(indexPath);
});
}, []);

if (!query.data) {
throw new Error('Suspense not called on useUser');
}
return query;
}
export function useUser() {
const navigate = useNavigate();
const query = useQuery({
queryKey: ['auth', 'useUser'],
queryFn: async () => {
// do some stuff and either return { user: data } || { user: null }
},
suspense: true,
});

useEffect(() => {
supabaseClient.auth.onAuthStateChange(async () => {
await query.refetch();
navigate(indexPath);
});
}, []);

if (!query.data) {
throw new Error('Suspense not called on useUser');
}
return query;
}
My problem is that useUser is called in multiple different places and the onAuthStateChange is called and set up several times. Is there any way that I can make it so that onAuthStateChange will only ever be called once? I could move it outside the component (top of the file) but I lose the ability to access query.refetch()
1 Reply
other-emerald
other-emeraldOP3y ago
Silly question, I think I can just move the useEffect to my App component and just useUser there

Did you find this page helpful?