this is my first using useReducer
and useContext
with Typescript
and I'm creating a simple counter. I'm trying to update the count
using increment and decrement dispatch but it doesn't change and no error in terminal.
Here is the link to codesandbox: codesandbox
Thank you
CodePudding user response:
When using context, the Provider
needs to be farther up the component tree than the consumer. The very top component in your code is App
, and it immediately tries to do useContext(CountContext)
. But since there is no provider above it, App just gets the default value of the context, which means dispatch
is an empty function () => {}
.
You will need to split your components up. Render the provider near the top of the tree, and then use it farther down the tree. For example:
function App() {
return (
<CountContextContainer>
<SomeChildComponent/>
</CountContextContainer>
);
}
function SomeChildComponent() {
const { state, dispatch } = useContext(CountContext);
const increment = () => {
dispatch({
type: ActionType.INCREMENT,
payload: 2
});
};
const decrement = () => {
dispatch({
type: ActionType.DECREMENT,
payload: 2
});
};
return (
<div className="App">
<p>Count: {state.count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}