I'm trying to learn how to use hooks and context in React, but need to work with TypeScript (new to that as well).
I am confused about what to set provider value on my below code. I have created a hook useFirebase it will return some functions like RegisterUser, SignIn, user(it's a state), logout.
First I created UseAuth.tsx hook, using this hook I want to import the above functions which I mentioned.
import { useContext } from 'react';
import { AuthContext } from '../context/AuthProvider';
const UseAuth = () => {
const auth = useContext(AuthContext)
return auth
};
export default UseAuth;
Everything is ok but I am getting an error on the provider value. The error is (JSX attribute) React.ProviderProps<null>.value: null Type '{ RegisterUser: RegisterUserFunction; SignIn: SignInUserFunction; user: userState; logout: () => void; }' is not assignable to type 'null'. The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<null>'
I have created an interface IAuth but where I need to define it I am confused.
import React, { createContext } from 'react';
import { UseFirebase } from '../hooks/UseFirebase';
export const AuthContext = createContext(null)
export interface IAuth {
RegisterUser: () => void;
SignIn : () => void;
user : any
logout : () => void;
}
const AuthProvider = ({ children } :any) => {
const allContext = UseFirebase()
return (
<AuthContext.Provider value={allContext}>
{children}
</AuthContext.Provider>
);
};
export default AuthProvider;
CodePudding user response:
The problem is in
export const AuthContext = createContext(null)
You need to pass a proper type to it, so it won't complain when trying to assign any value.
Try something like
React.createContext<IAuth>(initialValue);
For a more detailed explanation check out this article react-context-with-typescrip