Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 306
luis Colina Avatar asked Apr 18 '26 02:04

luis Colina


1 Answers

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, []);
like image 83
ontanj Avatar answered Apr 19 '26 16:04

ontanj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!