Why getting NaN on redux while adding a number

I am learning redux. I am trying to learn redux by increment decrementing value. I have written a code. While I am dispatching INCREMENT_BY_VALUE it is showing NaN But INCREMENT, DECREMENT and RESET are working properly.

Here is my code:

const { createStore } = require("redux")

const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
const RESET = 'RESET'
const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE"

const initialCounterState = {
  count: 0
}

const incrementCounter = () => {
  return {
    type: INCREMENT
  }
}

const decrementCounter = () => {
  return {
    type: DECREMENT
  }
}

const incrementByValue = (value) => {
  return {
    type: INCREMENT_BY_VALUE,
    action: value
  }
}

const resetCounter = () => {
  return {
    type: RESET
  }
}

const counterReducer = (state = initialCounterState, action) => {
  switch (action.type) {
    case INCREMENT:
      return {
        ...state,
        count: state.count + 1
      }

    case DECREMENT:
      return {
        ...state,
        count: state.count - 1
      }

      
    case RESET:
      return {
        ...state,
        count: 0
      }

    case INCREMENT_BY_VALUE:
      return {
        ...state,
        count: state.count + action.payload
      }

    default:
      break;
  }
}

const store = createStore(counterReducer)

store.subscribe(() => {
  console.log(store.getState());
})

store.dispatch(incrementCounter())
store.dispatch(decrementCounter())
store.dispatch(resetCounter())
store.dispatch(incrementByValue(10))

I am getting this output form my code:

{ count: 1 }
{ count: 0 }
{ count: 0 }
{ count: NaN }

Why is this happening and how can I fix that?

>Solution :

Your incrementByValue action creator returns an object with an action property, but in the reducer function, you are accessing the payload property, which does not exist. That is evaluated to undefined and adding that to a number results in NaN.

Either change the reduce to use the action property or make the action creator return an object with the payload property.

Leave a Reply