6

greetings im having a little of a trouble implementing an useReducer in a typeStript application, i have several mistakes (all of then on the reducer) but this one is the most commom throu the app, every single time that i call the dispatch function it jumps the error of "Expected 0 arguments, but got 1"

this is the function of the reducer

interface Edit {
  id?: number;
  todo?: string;
}

type Actions =
   { type: "add"; payload: string }
  | { type: "remove"; payload: number }
  | { type: "done"; payload: number }
  | { type: "all"; payload: Todo[] }
  | { type: "edit"; payload: Edit };

const reducerFunction = (state: Todo[], actions: Actions) => {
  const todoActions = {
    add: [...state, { id: Date.now(), todo: actions.payload, isDone: false }],
    edit: state.map((todo) =>
      todo.id === actions.payload.id
        ? { ...todo, todo: actions.payload.todo }
        : todo
    ),
    remove: state.filter((todo) => todo.id !== actions.payload),
    done: state.map((todo) =>
      todo.id === actions.payload ? { ...todo, isDone: !todo.isDone } : todo
    ),
    all: state = actions.payload
  };
  return todoActions[actions.type] ?? state;
};

the reducer and one of the dispatchs

  const [todos, dispatch] = useReducer(reducerFunction, []);
/*-----------*/
 dispatch({ type: "add", payload: todo });

you can watch the whole app in this codesanbox: https://codesandbox.io/s/trello-todo-component-clone-ebpqw4?file=/src/App.tsx:1465-1507

luis Colina
  • 61
  • 1
  • 5
  • It is a bad approach to create a todoActions object inside reducerFunction each key (add, edit, remove, done) will calculate the next state value on every call. – sultan May 31 '22 at 20:17
  • @sultan you're totally right, already added a switch case, thank you – luis Colina Jun 01 '22 at 12:12

1 Answers1

11

In order for TypeScript to infer the type of the state, you need to add a return type to reducerFunction.

const reducerFunction = (state: Todo[], actions: Actions): Todo[]

Alternatively, you can add the type of reducerFunction to the useReducer call.

const [todos, dispatch] = useReducer<(state: Todo[], actions: Actions) => Todo[]>(reducerFunction, []);
Anton
  • 1,045
  • 1
  • 7
  • 16