I wonder if this is a correct way to use immutable.js
with redux and reselect
(also redux-saga
). Specifically I wonder about toJS()
and from fromJS()
and where to use them.
My idea is that:
- I use
toJS()
when sending data to a saga. - I do not use
fromJS()
in reducer because I think that it is done anyway by the fact that I usefromJS()
for initialState. Or am I wrong about that? - I use
toJS()
in selector fromreselect
so I can use js data in react component.
Example:
1) In my react component I do:
// mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
loginRequest: values => dispatch(loginRequest(values)),
};
}
// Sending values.toJS() to my redux-saga.
submit = values => {
this.props.loginRequest(values.toJS());
};
2) In reducer I do (should one use fromJS()
here or not? According to redux docs you should):
const { fromJS } = require('immutable');
const state = fromJS({
pages: {
usersPage: {
loading: false,
isFetched: false,
list: [],
}
}
});
function reducer(state, action) {
switch(action.type) {
case 'USERS_LOADED':
return state
.setIn(['usersPage', 'list'], action.payload) // fromJS() here or not?
.setIn(['usersPage', 'isFetched'], true)
.setIn(['usersPage', 'loading'], false)
;
default:
return state;
}
}
export default reducer;
3) In my selector I do toJS()
again:
const selectUser = state => state.get('user', initialState);
const makeSelectList= () =>
createSelector(selectUser, userState => userState.getIn(['usersPage',
'list']).toJS());
// Which I then use in my react component:
const mapStateToProps = createStructuredSelector({
list: makeSelectList(),
});
So basically I wonder if that is a correct flow of convertion between js and immutable. Or can it be optimized in some way (less convertion steps)? Maybe the above is a non-optimal way of logic?
Best Regards