In redux-observable
is it possible to use isomporphic-fetch instead of Rx.DOM.ajax?
(Note: RX.DOM.ajax
is from RxJS v4, and doesn't work with redux-observable
which requires RxJS v5. The equivalent in v5 is Rx.Observable.ajax
or import { ajax } from 'rxjs/observable/ajax';
)
It is indeed possible to use fetch()
as well as any other AJAX API; though some adapt easier than others!
The fetch()
API returns a Promise
, which RxJS v5 has built-in support for. Most operators that expect an observable can consume Promises as-is (like mergeMap
, switchMap
, etc). But often you'll want to apply Rx operators to the Promise before passing it along to the rest of your Epic, so you'll often want to wrap the Promise inside an Observable.
You can wrap a Promise into an Observable with Observable.from(promise)
Here's an example where I fetch for a user, request the JSON response, then wrap the promise in an observable:
const api = {
fetchUser: id => {
const request = fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
.then(response => response.json());
return Observable.from(request);
}
};
You can then consume that in your Epic and apply any operators you want:
const fetchUserEpic = action$ =>
action$.ofType(FETCH_USER)
.mergeMap(action =>
api.fetchUser(action.payload) // This returns our Observable wrapping the Promise
.map(payload => ({ type: FETCH_USER_FULFILLED, payload }))
);
Here's a JSBin with this working example: https://jsbin.com/fuwaguk/edit?js,output
If you have control over the API code, ideally you would use Observable.ajax
(or any other Observable-based AJAX utils) because Promises cannot be cancelled. (as of this writing)
Did small adjustment to @jayphelps in order to get that code work for me. Hope this helps to save someone's time.
import { FETCH_USER } from './actions'
import { ofType } from 'redux-observable'
import { map, mergeMap } from 'rxjs/operators'
import { from } from 'rxjs'
const fetchUserEpic = action$ => {
return action$.pipe(
ofType(FETCH_USER),
mergeMap((action = { user: 'redux-observable' }) => {
const getRequest = (user) => {
const request = fetch(`https://api.github.com/users/${user}`)
.then(response => response.json())
return from(request)
}
return getRequest(action.user).pipe(
map(payload => ({ type: FETCH_USER_FULFILLED, payload }))
)
})
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With