Guest User

Untitled

a guest
Oct 18th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. // Watcher
  2. export function* onPageInit() {
  3. yield takeLatest(ON_PAGE_MOUNT, fetchDataForPage);
  4. }
  5.  
  6. // Saga
  7. export function* fetchDataForPage() {
  8. // Get any dependencies (from your store, or locally, etc)
  9. const userId = yield select(getUserId);
  10. const dependency = 42;
  11.  
  12. try {
  13. // error checking
  14. if (!userId) {
  15. throw new Error('No user - aborting');
  16. }
  17.  
  18. // run all fetch requests in parallel
  19. yield all([
  20. fork(requestAndPut, [firstRequest, userId], firstRequestActionCreator),
  21. fork(requestAndPut, [secondRequest, userId, dependency], secondRequestActionCreator),
  22. fork(requestAndPut, [thirdRequest, userId], thirdRequestActionCreator)
  23. ]);
  24. }
  25. catch (e) {
  26. // error handling
  27. yield put({ type: ON_PAGE_MOUNT_ERROR, payload: e });
  28. }
  29. }
  30.  
  31. // Helpers
  32. function* requestAndPut(requestParameters, actionCreator) {
  33. const result = yield call(...requestParameters);
  34. yield put(actionCreator(result));
  35. }
  36.  
  37. const firstRequest = (userId) => {
  38. return request(`${Config.api.base}/foo/bar`, { userId })
  39. .then(resp => resp.json());
  40. }
  41.  
  42. const firstRequestActionCreator = data => ({
  43. type: FETCH_FIRST_REQUEST_SUCCESS,
  44. payload: data
  45. });
  46. // .. and secondRequestActionCreator & thirdRequestActionCreator ...
Add Comment
Please, Sign In to add comment