i tried This pattern of including the dispatch functionality in my reducer function but i got this NaN whatever i try to increment or decrement what's the thing that i'm missing basically creating helper method in my reducer function for better api approach might not be the best approach but at least i tried things differently what's the problem that i'm missing in order for this to work [forgive my english]
import * as React from 'react';
const CounterContext = React.createContext();
function CounterProvider({ step = 1, initialCount = 0, ...props }) {
const [state, dispatch] = React.useReducer(
(state, action) => {
const change = action.step ?? step
switch (action.type) {
case 'increment': {
return { ...state, count: state.count + change }
}
case 'decrement': {
return { ...state, count: state.count - change }
}
default: {
throw new Error(`Unhandled action type:${action.type}`)
}
}
},
{ initialCount: initialCount })
const increment = React.useCallback(() => dispatch({ type: 'increment' }), [
dispatch
])
const decrement = React.useCallback(() => dispatch({ type: 'decrement' }), [
dispatch
])
const value = { increment, decrement, state }
return <CounterContext.Provider value={value} {...props} />
}
function useCounter() {
const context = React.useContext(CounterContext)
if (context === undefined) {
throw new Error('useCounter must be used within CounterProvider')
}
return context
}
function Counter() {
const { state, increment, decrement } = useCounter();
console.log(state, 'inc ', increment, 'dec ', decrement)
return (
<div>
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
<div>Current Count: {state.count}</div>
</div>
)
}
function App() {
return (
<CounterProvider>
<Counter />
</CounterProvider>
)
}
export default App