Skip to content

Instantly share code, notes, and snippets.

@dbashford
Last active January 20, 2022 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbashford/cc1af9a2c579fd5e4575 to your computer and use it in GitHub Desktop.
Save dbashford/cc1af9a2c579fd5e4575 to your computer and use it in GitHub Desktop.
Using both redux-immutablejs and redux-optimist

redux-optimist usage

import optimist from 'redux-optimist';
import { combineReducers } from 'redux';
import todos from './todos';

export default optimist(combineReducers({
  todos
}));

redux-immutablejs usage

import { combineReducers } from 'redux-immutablejs';
import * as reducers from './reducers';
export default combineReducers(reducers);

So the question is, how to use them together?

optimist wants to be called on the result of combineReducers from redux.

immutablejs wants to BE combineReducers. ImmutableJS' combineReducers transforms the resulting combined state tree into an ImmutableJS Map, so to get individual state out, you have to use ImmutableJS APIs. So I assumed this would be the way to go:

import { combineReducers } from 'redux-immutablejs';  // <= note this is redux-immut
import optimist from 'redux-optimist';
import * as reducers from './reducers';
export default optimist(combineReducers(reducers));

The error that occurs in the ImmutableJS combineReducers replacement when attempting to deal with state changes. state.get is undefined on the last line. get is a ImmutableJS function. The state passed in is expected to be an ImmutableJS object and in this case it isn't.

The reason it is not an ImmutableJS object is because optimist transforms/rebuilds the state internally which strips it of its ImmutableJS-ness. It turns the state vanilla and, understandably so, redux-immutable breaks attempting to access it.

Solution?

You can choose to not use this combineReducers and just use Immutable reducers. This means that you access each individual reducer by name, and its data using ImmutableJS APIs.

So this

mapStateToProps: (state) => {
  return { 
    initialSettings: state.getIn(['count', 'settings']) 
  };
}

turns into this

mapStateToProps: (state) => {
  return { 
    initialSettings: state.count.get('settings') 
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment