For some reason, logging out using Context doesn't throw any error. Yet when it comes to logging in I get an invalid hook call error upon submitting my sign in form.
this is the context code:
import { createContext, useState, useEffect, useContext } from "react";
import supabase from "../lib/supabase";
import { useRouter } from 'next/router';
const Context = createContext();
const Provider = ({ children }) => {
const router = useRouter();
const [user, setUser] = useState(supabase.auth.user())
useEffect(() => {
supabase.auth.onAuthStateChange(() => {
setUser(supabase.auth.user())
})
}, []);
const login = async () => {
try{
setLoading(true)
const { error } = await supabase.auth.signIn({email, password});
if (error) throw error
} catch (error) {
alert(error.error_description || error.message)
} finally {
setLoading(false);
}
}
const logout = async () => {
await supabase.auth.signOut();
setUser(null);
router.push('/app');
};
const exposed = {
user,
login,
logout,
}
return <Context.Provider value={exposed}>{children}</Context.Provider>;
};
export const useUser = () => useContext(Context);
export default Provider;
From the research I've done trying to solve it, it may be a problem with exporting and not having the useUser in a functional component, though I'm not sure why it's working for one and not the other.
and this is the error I get:
Unhandled Runtime Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
43 | };
44 |
> 45 | export const useUser = () => useContext(Context);
| ^
46 |
47 | export default Provider;
48 |
and these are the login/logout pages:
// this works
const Logout = () => {
const { logout } = useUser();
useEffect(() => logout, []);
return <p>Logging out</p>;
};
// throws error
const handleLogin = async (email, password, setLoading) => {
const { login } = useUser();
useEffect(() => login, []);
}