I am trying to make a login state globally for my ReactJS application with typescript. I declared the context in a file and imported to App.tsx file.
export const loginContext = createContext({});
In the App.tsx file I created a state and provided the variable and the function as object.
import { loginContext } from "./context";
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<loginContext.Provider value={{ isLoggedIn, setIsLoggedIn }}>
...
</loginContext.Provider>
)
Now I want to access the isLoggedIn
variable in another file
I tried to do so by writing,
import { loginContext } from "../context";
const { isLoggedIn, setIsLoggedIn } = React.useContext(loginContext);
But typescript is showing me the following error,
Property 'isLoggedIn' does not exist on type '{}'.
Property 'setIsLoggedIn' does not exist on type '{}'.
Any help would be appreciated
CodePudding user response:
You should define proper default values where you are creating the context. Something like this.
export const loginContext = createContext({
isLoggedIn: false,
setIsLoggedIn: (value: boolean): void => {}
});