Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why typescript is unable to identify value provided by the context wrapper?

I am trying to create a context wrapper. Pass the state variables as provider values and try to access those values using useContext in the ToolBar component.

type NavContextType = {
    isDrawerOpen: boolean;
    setIsDrawerOpen: React.Dispatch<React.SetStateAction<boolean>>;
};

export const NavContext = createContext<NavContextType | null>(null);

const NavBar: :ReactFC<ReactNode | undefined> = ({ children }) => {
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);

    return (
        <NavContext.Provider value={{ isDrawerOpen, setIsDrawerOpen }}>
            <ToolBar />
        </NavContext.Provider>
    );
};


Toolbar.js:

import { NavContext } from "./NavBar";

const ToolBar = () => {
    const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);
    return (
        .......
        .......
    );
};


when I try to access context values using const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);. I get typescript error as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TS2339: Property 'setIsDrawerOpen' does not exist on type 'NavContextType | null'.
        Property 'isDrawerOpen' does not exist on type 'NavContextType | null'.

Please guide me.

>Solution :

You need to use as directive for example useContext(NavContext) as NavContextType. Typescript will know, that the value is not null.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading