React-TypeScript: Expected 0 arguments, but got 1 on a useReducer
Asked Answered
U

1

10

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

Unbeliever answered 31/5, 2022 at 17:49 Comment(2)
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.Canard
@Canard you're totally right, already added a switch case, thank youUnbeliever
E
21

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, []);
Eighty answered 31/5, 2022 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.