Lets say I have a basic setup for checking whether a user is logged in or not:
import { createContext } from "react";
const UserContext = createContext<string | null>(null)
export default UserContext
In my App.tsx I want to create a useState hook so that I can manage the state of my context throughout my application:
//Context
const [context, setContext] = useState<string | null>(null)
<UserContext.Provider value={{context, setContext}}>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/login" element={<Login/>}/>
<Route path="/register" element={<Register/>}/>
<Route path="/admin" element={<Admin/>}></Route>
</Routes>
</UserContext.Provider>
So as far as I can see I'll only ever need either the name of the logged in user, or set the state of the context to null if I want to deny access to certain pages. Now the issue is that typescript is yelling at me here, specifically in the value of the Provider:
Type '{ context: string | null; setContext:
React.Dispatch<React.SetStateAction<string | null>>; }' is not assignable to type 'string'.ts(2322)
I can force cast the value as follows:
value={{context, setContext} as any}
But that doesn't seem like a particularly elegant 'typescripty' solution.
Any help is appreciated!
const UserContext = createContext<string | null>(null)
you are saying the value of your context is string or null but when you pass the value prop to the context provider you are passing an object with a context property that's string or null as well as a setter. You need to make the types match. Either just pass the context value fromuseState
to the provider or change the type of your call touseContext
to be an object with a string or null context property and a setter function. – Coursing