Skip to content

Example redux modules

Haz edited this page May 30, 2017 · 24 revisions

There're a bunch of redux modules already on the example app. Here's an explanation of each of them.

The entities module handles normalization through the normalizr library. The middleware does 3 things:

  • intercepts actions dispatched with meta.entities property;
  • normalizes the action payload property based on the value of meta.entities;
  • dispatches an ENTITIES_RECEIVE action with normalized entities, which will be handled by the entities reducer.

To be able to have an entity normalized, you need to do 3 things:

  • add meta.entities to the success action:

      const resourceCreateSuccess = (resource, detail) => ({
        type: RESOURCE_CREATE_SUCCESS,
        payload: detail,
    +   meta: {
    +     entities: resource,
    +   },
      })
  • create resource schema on store/entities/schemas.js

    export const resource = new schema.Entity('resource')
  • on containers, use selectors from the entities store instead of the resource one:

    - import { fromResource } from 'store/selectors'
    + import { fromResource, fromEntities } from 'store/selectors'
      ...
      const mapStateToProps = state => ({
    -   list: fromResource.getList(state, 'resource'),
    +   list: fromEntities.getList(state, 'resource', fromResource.getList(state, 'resource')),
      })

TODO

TODO

The resource has generic CRUD operations within redux.

Example action:

store.dispatch(resourceCreateRequest('posts', { title: 'foo' }))
                                      ^ resource endpoint

The first parameter (called resource) is important as it will be used both to call the API and to combine with other modules such as entities:

// The resulting action
{
  type: RESOURCE_CREATE_REQUEST,
  payload: { 
    data: {
      title: 'foo',
    },
  },
  meta: {
    resource: 'posts',
    thunk: 'postsCreate',
  },
}

// The resulting API call (inside saga)
const detail = yield call(api.post, '/posts', { title: 'foo' })

TODO

Clone this wiki locally