Skip to content

Example redux modules

Haz edited this page May 9, 2017 · 24 revisions

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

async

It's responsible for handling "pseudo-asynchronous" action creators. The middleware listens to action creators with *_REQUEST type dispatched with meta.done own property. Then, it returns a promise that will be fulfilled or rejected when the equivalent *_SUCCESS or *_FAILURE actions are dispatched.

Consider the following action creators:

export const resourceCreateRequest = (data, done) => ({
  type: 'RESOURCE_CREATE_REQUEST',
  payload: {
    data,
  },
  meta: {
    done,
  },
})

export const resourceCreateSuccess = (detail, request) => ({
  type: 'RESOURCE_CREATE_SUCCESS',
  payload: detail,
  meta: {
    request,
  },
})

When dispatching resourceCreateRequest, some saga will take it and make the request, dispatching resourceCreateSuccess when it's done. Since the request action had a meta.done property, the async middleware will handle it and return a promise from dispatch:

// on some container
store
  .dispatch(resourceCreateRequest({ title: 'Hello, World!' }))
  .then((detail) => {
    console.log('Yay! Resource was created!', detail)
  })

You can also provide the done callback function. In this case, the async middleware will not have effect:

store.dispatch(resourceCreateRequest({
  title: 'Hello, World!',
}, (err, detail) => {
  if (err) {
    return console.error(err)
  }
  return console.log('Yay! Resource was created!', detail)
}))
Clone this wiki locally