Skip to content

Instantly share code, notes, and snippets.

@papaponmx
Last active June 4, 2019 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save papaponmx/1b61ffebc0b49b7bedbf8e954cfb959e to your computer and use it in GitHub Desktop.
Save papaponmx/1b61ffebc0b49b7bedbf8e954cfb959e to your computer and use it in GitHub Desktop.
Introduction to Redux Observable
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;
}
import { baseUrl } from '../environment';
import { combineEpics } from 'redux-observable';
import { ajax } from 'rxjs/observable/dom/ajax';
// modules/list/index.js
// Actions
const FETCH_LIST = 'my-app/module/FETCH_LIST';
const FETCH_LIST_SUCCESS = 'my-app/module/FETCH_LIST_SUCCESS';
const FETCH_LIST_ERROR = 'my-app/module/FETCH_ERROR';
// Reducer
const InitialState = {
fetching: false;
list: [ ],
};
export default function reducer(state = {}, action = {}) {
switch (action.type) {
// do reducer stuff
default: return state;
}
}
// Action Creators
export function fetchList() {
return {
type: FETCH_LIST
};
}
export function fetchListSuccess(list) {
return {
type: FETCHING_LIST_SUCCESS,
payload: { list }
};
}
export function fetchListError(error) {
return {
type: FETCH_LIST_ERROR,
payload: error,
};
}
// Epic
const fetchListEpic = action$ => {
action$.ofType(FETCH_LIST_SUCCESS)
.mergeMap(action =>
ajax.getJSON(`${baseurl}/list`)
.map(res => fetchListSuccess(res.data))
);
};
// When you have many epics you might want to combine them like this
export const combineEpics(
fetchListEpic,
// Some other epics ...
);
import { combineEpics } from 'redux-observable';
import { combineReducers } from 'redux';
import list, { fetchListEpic } from './lists';
export const rootEpic = combineEpics(
fetchUserEpic,
// ...
);
export const rootReducer = combineReducers({
// ...
list,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment