Skip to content

Reducers and actions for storing collections of documents in Redux state

License

Notifications You must be signed in to change notification settings

jcoreio/redux-immutable-collections

Folders and files

NameName
Last commit message
Last commit date
Dec 21, 2017
Mar 6, 2017
Mar 6, 2017
Nov 10, 2016
Dec 10, 2016
Dec 10, 2016
Oct 3, 2016
Oct 12, 2016
Dec 8, 2016
May 19, 2016
Mar 6, 2017
Dec 21, 2017
Dec 12, 2016
Dec 21, 2017

Repository files navigation

redux-immutable-collections

Build Status Coverage Status semantic-release

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: 'jim@bob.com',
}))

console.log(store.getState())

The state will look like this:

Map {
  "users": Map {
    "28nkdjas9i23kjsdaf": Map {
      "username": "jimbob",
      "firstName": "Jim",
      "lastName": "Bob",
      "email": "jim@bob.com"
    }
  },
  "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: 'jim@bob.com',
  }),
]))

There is a clear action as well that will clear the collection.

About

Reducers and actions for storing collections of documents in Redux state

Resources

License

Stars

Watchers

Forks

Packages

No packages published