Dennis
Dennis

Reputation: 59

how to use redux-observerable when the network requset handle by axios

I want to use redux-observerable to my project,because the action of if can be canceld.But the offical gives the example which uses the ajax of rxjs, I want to use axios as the network library, how to realize it.

the example code:

const FETCH_USER = 'FETCH_USER';
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
const FETCH_USER_REJECTED = 'FETCH_USER_REJECTED';
const FETCH_USER_CANCELLED = 'FETCH_USER_CANCELLED';

const fetchUser = id => ({ type: FETCH_USER, payload: id });
const fetchUserFulfilled = payload => ({ type: FETCH_USER_FULFILLED, payload });
const cancelFetchUser = () => ({ type: FETCH_USER_CANCELLED });

const fakeAjax = url => of({
  id: url.substring(url.lastIndexOf('/') + 1),
  firstName: 'Bilbo',
  lastName: 'Baggins'
}).pipe(delay(1000));

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => fakeAjax(`/api/users/${action.payload}`).pipe(
    map(response => fetchUserFulfilled(response)),
    takeUntil(action$.pipe(
      filter(action => action.type === FETCH_USER_CANCELLED)
    ))
  ))
);

const users = (state = {}, action) => {
  switch (action.type) {
    case FETCH_USER:
        return {};

    case FETCH_USER_FULFILLED:
      return {
        ...state,
        [action.payload.id]: action.payload
      };

    default:
      return state;
  }
};

const isFetchingUser = (state = false, action) => {
  switch (action.type) {
    case FETCH_USER:
      return true;

    case FETCH_USER_FULFILLED:
    case FETCH_USER_CANCELLED:
      return false;

    default:
      return state;
  }
};

I want replace fetchAjax use axios

const fakeAjax = url,params =>{ return axios({
        method: 'post',
        url: url,
        data: params
    });
}

Upvotes: 1

Views: 156

Answers (1)

dentemm
dentemm

Reputation: 6379

I don't understand the added value of using axios, since ajax from rxjs will simplify your code (it is already using observables). However, if you really want to it is definitely possible. I assume in the example below that you are using actions where the payload consists of a url and request data.

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => from(axios({method: 'get', action.payload.url, data: action.payload.data})).pipe(
    map(response => fetchUserFulfilled(response)),
    takeUntil(action$.ofType(FETCH_USER_CANCELLED)),
  ))
);

Also: keep in mind that cancelling will prevent the redux store from being updated, but it will not cancel the axios request from being processed.

Upvotes: 2

Related Questions