Last active
August 31, 2017 13:33
-
-
Save mohandere/c17cb25f40f991936bd41c9a3d283fbf to your computer and use it in GitHub Desktop.
Writing epics with redux-observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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