Kamyar Parastesh Kamyar Parastesh - 1 month ago 6
React JSX Question

Uncaught TypeError: Cannot create property 'activeWord' on number '0'

in my react application, i have pre-loaded a reducer called

activeWord
.

activeWord: 0


Then i have added the
activeWord
in the root reducer

import {combineReducers} from 'redux';
import activeWord from './ActiveWordReducer';

const root_reducer=combineReducers({

activeWord:activeWord
});

export default root_reducer;


And then in
ActiveWordReducer
file:

export default function WordReducer(state=null,action){
switch(action.type){
case "Active_Word":
return state.activeWord++;
}
return 0;
}


The problem is, in the line
state.activeWord++
, it generates an error:

Uncaught TypeError: Cannot create property 'activeWord' on number '0'


So how can i fix this issue?

Update:

in the reducer i also tried to return state but still i got the same error:

export default function WordReducer(state=null,action){
switch(action.type){
case "Active_Word":
return state.activeWord++;
}
return state;
}

Answer

There are three problems that I would like to mention:

  • Function combineReducers takes an object, where key is the name of the reducer function and the value is the name of the property of state that should be passed to that reducer. So, for your case, it should be like, const root_reducer = combineReducers({ activeWord: activeWord }); But, if its the case that you've a reducer called activeWord which ultimately calls that WordReducer, then please ignore this suggestion. And maybe, you'd like to rename WordReducer to wordReducer.
  • In your WordReducer function, state now represents activeWord. So, it's just a number. That's why you are getting that error.
  • Do not mutate your object. Just return state + 1. And keep constant all caps.

So, your reducer should look like, export default function WordReducer(state = 0, action) { switch(action.type) { case "ACTIVE_WORD": return state + 1; default: return state; } }