redux-immutable-collections
v3.0.0
Published
Reducers and actions for storing collections of documents in Immutable.js collections in Redux state.
Downloads
10
Maintainers
Readme
redux-immutable-collections
Reducers and actions for storing collections of documents in Immutable.js collections in Redux state. Designed for Mongo documents, but potentially useful even if you're not using Mongo.
Usage
npm i --save redux-immutable-collections
Keyed collections
import {reducer as keyedCollectionReducer, actions} from './lib/keyedCollection'
import {createStore} from 'redux'
import {combineReducers} from 'mindfront-redux-utils-immutable'
const USERS = 'USERS.'
const POSTS = 'POSTS.'
// the keyed collection action types are just INSERT, UPDATE, REMOVE, and BATCH,
// unless we specify an action type prefix like so:
const reducer = combineReducers({
users: keyedCollectionReducer({actionTypePrefix: USERS}),
posts: keyedCollectionReducer({actionTypePrefix: POSTS}),
})
const userActions = mapValues(actions(USERS))
const postActions = mapValues(actions(POSTS))
const store = createStore(reducer)
store.dispatch(userActions.insert('28nkdjas9i23kjsdaf', {
username: 'jimbob',
firstName: 'Jim',
lastName: 'Bob',
}))
store.dispatch(userActions.update('28nkdjas9i23kjsdaf', {
email: '[email protected]',
}))
console.log(store.getState())
The state will look like this:
Map {
"users": Map {
"28nkdjas9i23kjsdaf": Map {
"username": "jimbob",
"firstName": "Jim",
"lastName": "Bob",
"email": "[email protected]"
}
},
"posts": undefined
}
You can also remove
documents:
store.dispatch(userActions.remove('28nkdjas9i23kjsdaf'))
If you need to make a lot of changes rapidly, dispatch them in a batch; the reducer will handle them inside a
withMutations
call, which is much more efficient, and redux subscribers will only be notified once:
store.dispatch(userActions.batch([
userActions.insert('28nkdjas9i23kjsdaf', {
username: 'jimbob',
firstName: 'Jim',
lastName: 'Bob',
}),
userActions.update('28nkdjas9i23kjsdaf', {
email: '[email protected]',
}),
]))
There is a clear
action as well that will clear the collection.