Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in redux when executing an action: Uncaught type error: cannot read property 'type' of undefined

Just new to React. I guess It's a basic question but I can't get why the reducer doesn't get fired or update the state:

My HomeView.js:

     ....
          const { localeChange, counter, locale } = this.props
            return (
               <div>
                  <button onClick={() => increment(7)}>Increment</button>
              <input type='text' value = {counter}/>
               .....
            </div>
        )

    const mapStateToProps = (state) => ({
      locale: state.locale,
      counter: state.counter
    })
    export default connect(mapStateToProps, {localeChange, increment})(HomeView)

My reducer (constant, action and reducer in the same file):

export const COUNTER_INCREMENT = 'COUNTER_INCREMENT'

export function increment (text) {
  return { type: COUNTER_INCREMENT, text }
}

export default function counterIncrement (state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + action.text
    default:
      return state
  }
}

And finally my "parent" reducer:

import { combineReducers } from 'redux'
import { routeReducer as router } from 'react-router-redux'
import locale from './modules/locale'
import counter from './modules/counter'

export default combineReducers({
  locale,
  router,
  counter
})

What I understand:

In my state I have a field named counter (it's there using redux dev tools). When I click the button I dispatch increment action, so I really should dispatch an action like this: {type: COUNTER_INCREMENT, text: 7}

However counterIncrement function (reducer) gets action as undefined: Uncaught type error: cannot read property 'type' of undefined. Any way I could debug this properly? I put a breakpoint in the reducer counterIncrement but doesn't get fired.

like image 866
user2670996 Avatar asked Feb 15 '16 23:02

user2670996


1 Answers

Redux validate that every action you trigger actually contains a type property.

My guess is that you're calling dispatch() with undefined. Your example code doesn't contains any dispatch calls, so I won't be able to help further - but my guess is that it'll be trivial to figure out. Either you call dispatch() with the wrong arguments, or your action creator doesn't return an object with a type property.

Side note (unrelated to your question), but your action creator type label doesn't match the one inside your reducer.

like image 171
Simon Boudrias Avatar answered Sep 20 '22 03:09

Simon Boudrias