So I'm trying to learn how to use context since I'm building a dating app for dogs just as a fun project and will have to pass the current user throughout the whole application.
Tho i don't seem to grasp how to use context with typescript. I have a component called HomeView and would like to view counter and possibly set the counter with the usestate function setCounter.
When I try to log the counter in my HomeView components all I get is undefined even tho the value is set to 0. I should be able to log 0 onto the screen in my consumer. What am I missing?
Contex.tsx
import { createContext, useState } from 'react';
type ContextType = {
setCounter: React.Dispatch<React.SetStateAction<number>>;
counter: number;
};
export const CounterContext = createContext<ContextType>({} as ContextType);
export const CounterContextProvider: React.FC = ({ children }) => {
const [counter, setCounter] = useState(0);
return <CounterContext.Provider value={{ counter, setCounter }}>{children}</CounterContext.Provider>;
};
HomeView.tsx
export const HomeView = () => {
const context = useContext(CounterContext);
console.log(context.counter); // value is undefined
return (
<div className='signInWrapper'>
<SignIn />
<CounterContextProvider>
{context.counter} // Nothing is shown onto the screen
</CounterContextProvider>
</div>
);
};
CodePudding user response:
Since you are retrieving the context in a component which is not nested in the CounterContext.Provider
itself you are getting undefined
.
You should nest your entire application in the CounterContextProvider
in order to access the state globally.
You can do this in your App.js
file:
function App() {
return (
<CounterContextProvider>
...
<HomeView/>
</CounterContextProvider>
After this you should be able to access the context in your HomeView
component:
export const HomeView = () => {
const { counter, setCounter } = useContext(CounterContext);
return (
<div className='signInWrapper'>
<SignIn />
Your counter value is: {counter}
</div>
);
};