简体   繁体   中英

How to fix property does not exist on '{}' with react typescript?

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

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 => {}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM