akornev
akornev

Reputation: 27

useReducer. Dispatch is not a function

In my example when I click button I have error "dispatch is not a function". Please tell my why? How correct set dispatch in props? Do I need always use useContext for that?

source (codesandbox)

App.tsx

const counterReducer = (state, action) => {
  switch (action) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
};

export default function App() {
  const [counter, dispatch] = useReducer(counterReducer, 1);

  return (
    <div className="App">
      <CounterView counter={counter} />
      <Buttons dispatch={dispatch} />
    </div>
  );
}

CounterView.tsx

export const CounterView = ({ counter }) => {
  return (
    <div>
      <h1>Counter: {counter}</h1>
    </div>
  );
};

Buttons.tsx

export const Buttons = (dispatch) => {
  return (
    <div>
      <button type="button" onClick={() => dispatch("INCREMENT")}>
        +1
      </button>
      <button type="button" onClick={() => dispatch("DECREMENT")}>
        -1
      </button>
    </div>
  );
};

Upvotes: 0

Views: 763

Answers (2)

prasanth
prasanth

Reputation: 22500

You are passing dispatch as props but in this button component you calling direct variable. So you need get the props of dispatch like below

export const Buttons = ({dispatch}) => {
  return (
    <div>
      <button type="button" onClick={() => dispatch("INCREMENT")}>
        +1
      </button>
      <button type="button" onClick={() => dispatch("DECREMENT")}>
        -1
      </button>
    </div>
  );
};

Upvotes: 1

Bjorne
Bjorne

Reputation: 1484

Dispatch is passed in the props.

export const Buttons = props => {
  return (
    <div>
      <button type="button" onClick={() => props.dispatch("INCREMENT")}>
        +1
      </button>
      <button type="button" onClick={() => props.dispatch("DECREMENT")}>
        -1
      </button>
    </div>
  );
};

or

export const Buttons = ({dispatch}) => {
  return (
    <div>
      <button type="button" onClick={() => dispatch("INCREMENT")}>
        +1
      </button>
      <button type="button" onClick={() => dispatch("DECREMENT")}>
        -1
      </button>
    </div>
  );
};

Upvotes: 1

Related Questions