Skip to content

Instantly share code, notes, and snippets.

@mohandere

mohandere/epic.js

Last active Aug 31, 2017
Embed
What would you like to do?
Writing epics with redux-observable
import * as ajax from '../../utils/ajax';
import 'rxjs/add/operator/catch'
import {
Observable
} from 'rxjs/Observable';
import queryString from 'query-string'
import _ from 'lodash'
import {
PRODUCTS_REQUEST_START,
CANCEL_PRODUCTS_REQUEST
} from '../actions/actionTypes';
import {
doFetchProductsFulfilled
} from '../actions/doFetchProducts';
// import { push } from 'react-router-redux';
export default function epicFetchProducts(action$, store) {
return action$.ofType(PRODUCTS_REQUEST_START)
.map(function(action) {
// Get existing selections/filters attributes from store
const currentSelections = store.getState().catalogReducer.currentSelections
// Now extend/override old atts with new attributes coming through action
const selections = Object.assign({}, currentSelections, action.newSelections)
const searchString = queryString.stringify(selections, {
arrayFormat: 'bracket'
})
// Push new search query by excluding default params
window.appHistory.push({
search: queryString.stringify(selections)
})
// Return new `action` object with new key `searchString` to call API
return Object.assign({}, action, {
searchString
})
})
.mergeMap(action =>
ajax.get(`/products?${action.searchString}`)
.map(response => doFetchProductsFulfilled(response))
.catch(error => doFetchProductsError(error))
.takeUntil(action$.ofType(CANCEL_PRODUCTS_REQUEST))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.