I have a counter like this :
import { useReducer } from 'react';
type CounterState = {
count: number;
};
type UpdateAction = {
type: 'increment' | 'decrement';
payload: number;
};
type ResetAction = {
type: 'reset';
};
type CounterAction = UpdateAction | ResetAction;
const initialState = { counter: 0 };
function reducer(state: CounterState, action: CounterAction) {
switch (action.type) {
case 'increment':
return { count: state.count + action.payload };
case 'decrement':
return { count: state.count - action.payload };
case 'reset':
return initialState;
default:
return state;
}
}
export const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return(
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment', payload: 10 })}>
Increment 10
</button>
<button onClick={() => dispatch({ type: 'decrement', payload: 10 })}>
Decrement 10
</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}
If I hover on useReducer(reducer, initialState)
, it says :
"No overload matches this call.
Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error. Argument of type '(state: CounterState, action: CounterAction) => { counter: number; } | CounterState' is not assignable to parameter of type 'ReducerWithoutAction'. Overload 2 of 5, '(reducer: (state: CounterState, action: CounterAction) => { counter: number; } | CounterState, initialState: never, initializer?: undefined): [...]', gave the following error.
Argument of type '{ counter: number; }' is not assignable to parameter of type 'never'"
In addition, hovering on dispatch({ type: 'increment', payload: 10 })
, it says :
Expected 0 arguments, but got 1.
What is the reason for this? I thought passed arguments were correct.
You just need to rename your initial state from counter to count as follow:
const initialState = { count: 0 };