Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading