Skip to content

Instantly share code, notes, and snippets.

@mohandere
Last active August 31, 2017 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohandere/c17cb25f40f991936bd41c9a3d283fbf to your computer and use it in GitHub Desktop.
Save mohandere/c17cb25f40f991936bd41c9a3d283fbf to your computer and use it in GitHub Desktop.
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