With Redux-observable, we had the power of RxJS at our disposal-this means tasks that would otherwise is complicated an D imperative, become simple and declarative. In this lesson we'll respond to a action by queuing up 2 separate Ajax requests that'll execute sequentially. Then we'll group the results from both to an array and produce a single action from our epic that would save the data int o The Redux Store
// Action = ' fetch_stories '= ' fetch_stories_fulfilled 'function fetchstoriesaction (count = 5) { return { type:fetch_stories, payload:count function fetchstoriesfulfilledaction (stories) { return { Type:fetch_stories_ Fulfilled, payload:stories }}
//EpicsImport {Observable} from' Rxjs '; import {combineepics} from' Redux-observable '; import {fetch_stories, fetchstoriesfulfilledaction} from".. /actions/index "; Const Topstories= ' https://Hacker-news.firebaseio.com/v0/topstories.json?print=pretty ';Const URL = (id) = = ' https://Hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty ';functionFetchstoriesepic (action$) {returnAction$.oftype (fetch_stories). Switchmap (({payload})= { returnObservable.ajax.getJSON (topstories)//Slice first 5 IDs. map (ids = Ids.slice (0, 5)) //convert IDs to URLs. map (ids =ids.map (URL))//convert URLs, Ajax. map (urls = urls.map (url =Observable.ajax.getJSON (URL))) //Execute 5 AJAX requests. Mergemap (reqs =Observable.forkjoin (reqs))//Store Results. Map (Stories =fetchstoriesfulfilledaction (Stories)})} Export Const Rootepic= Combineepics (fetchstoriesepic);
Import {fetch_stories, fetch_stories_fulfilled} from ". /actions/index "; Const Initialstate={stories: [], Loading:false,};exportfunctionStoriesreducer (state =Initialstate, Action) { Switch(action.type) { Casefetch_stories:return{stories: [], Loading:true }; Casefetch_stories_fulfilled:return{stories:action.payload, loading:false }; default:returnState ; }}exportdefaultStoriesreducer;
//ComponentImport React from' React '; import {connect} from"React-redux"; import {fetchstoriesaction} from".. /actions/index "; exportfunctionStories (props) {if(props.loading) {return ( <p>please wait...</p> ) } return ( <div> <button type= "button" onclick={props.loadstories}>load Top 5 stories</button> <storyl Ist stories={props.stories}/> </div> )}functionstorylist (props) {return ( <ul>{Props.stories.map ( Story= <li key={story.id}> <a href={story.url}>{story.title}</a> </li> )} </ul> );}functionMapstate (state) {returnState ;}functionMapdispatch (Dispatch) {return{loadstories: ()=Dispatch (Fetchstoriesaction ())}} ExportdefaultConnect (Mapstate, Mapdispatch) (Stories);
[React] Create a queue of Ajax requests with redux-observable and group the results.