Reputation:
I want to use a context within my React Typescript project, how can I do that?
I have the following code: App.js
import {Context} from 'context'
const App = () => {
const [value, setValue] = useState("");
return (
<Router>
<Context.Provider value={{value, setValue}}>
... some routes
</Context.Provider>
</Router>
)
}
Then in my context.js file I have:
import {createContext} from 'react';
type ValueContextType = {
value: string;
setValue: (value: string) => void;
}
export const ValueContext = createContext<ValueContextType | undefined>(undefined);
And I want to use this to set a state in another file. Let's say users.js
import {ValueContext} from 'context'
const Users () => {
const {value, setValue} = useContext(ValueContext);
}
Now the problem that both value and setValue have the same error message:
Property 'setValue' does not exists on type 'ValueContextType | undefined'
How can I make this work?
Upvotes: 2
Views: 992
Reputation:
I have found a solution that works:
App.js
import {Context} from 'context'
const App = () => {
type ValueContextType = {
value: string;
setValue: (value: string) => void;
}
const [value, setValue] = useState<ValueContextType | any>("");
return (
<Router>
<Context.Provider value={{value, setValue}}>
... some routes
</Context.Provider>
</Router>
)
}
Then in my context.js file I have:
import {createContext} from 'react';
type ValueContextType = {
value: string;
setValue: (value: string) => void;
}
export const ValueContext = createContext<ValueContextType | any>("");
users.js
import {ValueContext} from 'context'
const Users () => {
const {value, setValue} = useContext(ValueContext);
}
I don't know if this is "hacky" or not, but it works.
Upvotes: 1