Home > Back-end >  Can't setup useReducer with React/TypeScript
Can't setup useReducer with React/TypeScript

Time:04-24

I'm learning TypeScript. I'm trying to set up useReducer but I'm having a hard time doing it. The fix is probably fairly simple, so sorry for that. This is my App.tsx:

import React, { useReducer } from "react";
import { StartPage } from "./components/StartPage";
import { QuestionsPage } from "./components/QuestionsPage";

type State = {};

type Action = {};

const initialState = {
  hasStarted: false // one of the states I'm going to need
};

const reducer = (state: State, action: Action) => {};

export const App = () => {
  const [state, dispatch] = useReducer(reducer, initialState); // * error here

  return (
    <>
      <StartPage dispatch={dispatch}/>
      <QuestionsPage />
    </>
  );
};

(Perhaps) good to know: I'm trying to set it up in a basic way first, but later I want to conditionally render either StartPage.tsx or QuestionsPage.tsx based on whether hasStarted is true or false (which I'm going to set up in StartPage.tsx.

I'm getting the following error here (see * in code snippet above):

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: State, action: Action) => void' is not assignable to parameter of type 'ReducerWithoutAction'.
Overload 2 of 5, '(reducer: (state: State, action: Action) => void, initialState: never, initializer?: undefined): [never, Dispatch]', gave the following error.
Argument of type '{}' is not assignable to parameter of type 'never'.

CodePudding user response:

You are getting an error in Typescript because you are not returning any state inside the reducer function. This would do the fix:

const reducer = (state: State, action: Action) => {
 //...logic for updating the state
 return state; 
};
  • Related