3.0.0 • Published 6 years ago

redux-immutable-collections v3.0.0

Weekly downloads
7
License
MIT
Repository
github
Last release
6 years ago

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.

3.0.0

6 years ago

2.2.0

7 years ago

2.1.0

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago