A quick explanation of Redux Observable.
Jaime Rios
Posted on June 10, 2018
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:
- The component is rendered with props that are mapped from the store.
- An action is triggered by some event. This can be a DOM event or lifecycle method i.e.
componentWillMount()
. - 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. - Reducers reflect return a new state.
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))
);
};
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,
});
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;
}
In case you missed it, here is the link to all the code in one page.
That's all folks.
Posted on June 10, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.