How should I fix the problem with createContext? It expects some arguments, but I can't see what arguments. I tried giving it some dummy currentUser: undefined variables and it kinda works, but I can't figure out what should I do with other defaultValues like login, signup etc. It's based on JS Auth tutorial, and in JS it works, but I would like it to work on TSX. Thanks in advance, code below
AuthContext.tsx
const AuthContext = createContext()
export function useAuth() {
return useContext(AuthContext);
}
export default function AuthProvider( {children}:any ) {
const [currentUser, setCurrentUser] = useState();
function signup(email: string, password: string) {
return supabase.auth.signUp({
email: email,
password: password,
})
}
function login(email: string, password: string) {
return supabase.auth.signInWithPassword({
email: email,
password: password,
})
}
function logout() {
return supabase.auth.signOut()
}
function recoverPassword(email: string) {
return supabase.auth.resetPasswordForEmail(email);
}
function update(data: any) {
return supabase.auth.updateUser(data)
}
const value = {
currentUser, login, signup, logout, recoverPassword, update
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}
CodePudding user response:
You can either type createContext
with YourInterface | null
as in
const AuthContext = createContext<YourInterface|null>(null);
or type cast an empty object as in
const AuthContext = createContext({} as YourInterface)
CodePudding user response:
Create an interface that describes the data you want to store in the context:
interface AuthContextType {
currentUser: IUser;
login: (email: string, password: string) => ......,
signup: (email: string, password: string) => ....,
logout: () => void,
recoverPassword: (email: string) => ....,
update: (data: any) => ....
}
Create an object that describes the initial state:
const initialState = {
currentUser: null,
login: (email: string, ....) => console.error('No AuthProvider supplied. Wrap this component with a AuthProvider to use this functionality.'),
...
};
Then create the context:
const AuthContext = createContext<AuthContextType>(initialState);