A quick explanation of Redux Observable.

papaponmx

Jaime Rios

Posted on June 10, 2018

A quick explanation of Redux Observable.

Intro

The link to all the code in one page.

As a Front End Developer, I'm quite familiar with Redux, how it works and how to handle asynchronous operations with redux-saga.

However, in my new job we use redux-observable. I found it interesting, and some friend of mine was asking, therefore, here is a brief explanation of how it works with Redux.

Note: I'm assuming that you are comfortable with Redux jargon(action creators, reducers, store) and React.

Unidirectional data flow with observables.

The magic happens in the following order:

  1. The component is rendered with props that are mapped from the store.
  2. An action is triggered by some event. This can be a DOM event or lifecycle method i.e. componentWillMount().
  3. Actions are filtered by a reducer. At the same time, some epic listens to and acts on some action. Here is where async magic happens. Inside the epic, we can dispatch a new action if needed.
  4. Reducers reflect return a new state.

Here is a quick diagram
alt text

How it looks like in code. Following the redux-ducks pattern, I'll put everything in the same file.



// module/index.js
// Actions
...
// Reducer
...

// Action Creators
...

// Epics
const createEpic = action$ => {
 action$.ofType(FETCH_LIST_SUCCESS)
    .mergeMap(action =>
      ajax.getJSON(`${baseurl}/list`)
        .map(res => fetchUserSuccess(res.data))
    );
}; 



Enter fullscreen mode Exit fullscreen mode

With the epic logic and module in order. The next step is to add it to our root reducer and epic.



import { combineEpics } from 'redux-observable';
import { combineReducers } from 'redux';
import list, { fetchListEpic } from './lists';

export const rootEpic = combineEpics(
  fetchUserEpic,
  // ...
);

export const rootReducer = combineReducers({
  // ...
  list,
});



Enter fullscreen mode Exit fullscreen mode

In the end, redux-observable is just some middleware we use to handle async operations and side effects. The last step is to add it to our configureStore.js.



import { createStore, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { rootEpic, rootReducer } from './modules';

const epicMiddleware = createEpicMiddleware(rootEpic);

export default function configureStore() {
  const store = createStore(
    rootReducer,
    applyMiddleware(epicMiddleware)
  );


  return store;
}



Enter fullscreen mode Exit fullscreen mode

In case you missed it, here is the link to all the code in one page.

That's all folks.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
papaponmx
Jaime Rios

Posted on June 10, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About