2

I have a very simple code for incrementing and decrementing when + or - buttons are pressed. but whenever I press the buttons, I receive the error. I've been working on it for about 4 hours and can't find out why. I'm pretty sure that I'm not doing any async actions and my actions are returning JavaScript objects

actions code:

export const increment = () => {
    return { type: 'INCREMENT' }
}

export const decrement = () => {
    return { type: 'DECREMENT' }
}

reducer code:

export default function counterReducer(state = 0, action) {
    switch (action.type) {
      case 'INCREMENT':
        return state + 1
      case 'DECREMENT':
        return state - 1
      default:
        return state
    }
  }

app component code:

import React from "react";
import {decrement, increment } from "./actions";
import { useSelector, useDispatch } from "react-redux";
export default function App() {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(increment)}>+</button>
      <button onClick={() => dispatch(decrement)}>-</button>
      <p>{counter}</p>
    </div>
  );
}

Much appreciated.

3 Answers 3

3

You are dispatching action creator functions not the actions

The increment and decrement functions are called action creators. They return the action object.

You should call the action creator function for dispatching an action.

<button onClick={() => dispatch(**increment()**)}>+</button>
Sign up to request clarification or add additional context in comments.

Comments

3

In Redux, actions are objects. You have to execute actions functions into dispatch: dispatch(increment) could be dispatch(increment())

Comments

0

That problem is solved by using a middleware like redux-thunk or saga in the store configuration.

import { createStore, applyMiddleware } from "redux";

import rootReducer from "../reducers";
import thunk from "redux-thunk";

//Applying redux-thunk solves the problem
//Actions must be plain objects. Use custom middleware for async actions.

export const store = createStore(rootReducer, applyMiddleware(thunk));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.