Home > other >  React useReducer typeScripts
React useReducer typeScripts

Time:10-07

Hi every one i'm learning React hooks with typeScript and I have trubles with useReducer I've understood the how does it work but I have errors when I'm implementing it in my project.

const initalState: Istate = {
  counter: 1,
  name: "tt",
};
enum ActionKind {
  increase = "INCREASE",
  decrease = "DECREASE",
}
interface Action {
  type: ActionKind;
  payload: number;
}
interface Istate {
  counter: number;
  name: string;
}

function reducer(state: Istate, action: Action) {
  switch (action.type) {
    case "INCREASE":
      return { count: state.counter   1, name: state.name };
  }
}

export function Hooktest() {
  const [state, dispatch] = useReducer(reducer, initalState);

  return (
    <>
      <button onClick={increment}>{counter}</button>
    </>
  );
}

I don't realy understand the eroor or what I've done wrong

enter image description here

Thank you for your help

CodePudding user response:

The reducer should always return a state. Add a default to your switch. In addition, you have a typo in this line:

    return { count: state.counter   1, name: state.name };

The key count should be counter according to your type.

This is how your reducer should look:

function reducer(state: Istate, action: Action) {
  switch (action.type) {
    case "INCREASE":
      return { counter: state.counter   1, name: state.name };

    default:
      return state;
  }
}

Your Hooktest component should use the dispatch with relevant action from ActionKind enum:

export function Hooktest() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <button onClick={() => dispatch({ type: ActionKind.increase })}>
        {state.counter}
      </button>
    </>
  );
}

And you should change the Action type's payload to optional, since you don't action need payload for the INCREASE action:

interface Action {
  type: ActionKind;
  payload?: number;
}

You can see a working example in this Sandbox.

  • Related