bier hier
bier hier

Reputation: 22540

How to update reducer with right state?

In my react/redux app I have this reducer:

import {fromJS} from 'immutable';

import {
  CHANGE_USERNAME,
  ADD_COUNTER
} from './constants';

// The initial state of the App
const initialState = fromJS({
  username: '',
  counter:0
});

function homeReducer(state = initialState, action) {
  switch (action.type) {
    case CHANGE_USERNAME:
      // Delete prefixed '@' from the github username
      return state
        .set('username', action.name.replace(/@/gi, ''));
    case ADD_COUNTER:
      return state
        .set('counter',state.counter+1)
    default:
      return state;
  }
}

export default homeReducer;

Currently it hits the reducer but no state has been updated for the counter. What am I missing? link to code

Upvotes: 1

Views: 114

Answers (1)

David Bradshaw
David Bradshaw

Reputation: 13077

Your using immutable.js so you have to use get to read the value

return state.set(‘counter’, state.get(‘counter’) + 1)

Also your code is importing fromJS, but not using it.

Immutable.js has a very non JavaScripty syntax to it and if your not used to it and really want to play with immutability in Redux I would suggest looking at using Mori-Redux or seamless-immutable instead, both of which let you proper js syntax.

Upvotes: 1

Related Questions