Redux Appropriations Call for Cancellation

I have a React Native app with Redux actions and reducers. I use dispx-thunk dispatch to wait for asynchronous calls. There is an action in my application:

export const getObjects = (id, page) => {
    return (dispatch) => {
        axios.get(`URL`)
            .then(response => {
                dispatch({ type: OBJECTS, payload: response });
            }).catch(error => {
                throw new Error(`Error: objects -> ${error}`);
            });
    };
};

This works correctly, but sometimes the user presses the back button before the action completes the request and I must cancel it. How can I do this in a separate action? I read this , but I did not find any option in axios to interrupt. I read about axios cancellation , but it creates a cancellation method in the function area, and I cannot return, because JS do not support multiple returns.

What is the best way to cancel an axios request in another Redux action?

+4
1

- RxJS + Redux Observables, .

, , redux-thunk, .

, , .

A redux-observable epic RxJS Observable. , .takeUntil() ajax , MY_STOPPING_ACTION, , , , react-router-redux :

import { Observable } from 'rxjs';

const GET_OBJECTS = 'GET_OBJECTS';
const GET_OBJECTS_SUCCESS = 'GET_OBJECTS_SUCCESS';
const GET_OBJECTS_ERROR = 'GET_OBJECTS_ERROR';
const MY_STOPPING_ACTION = 'MY_STOPPING_ACTION';

function getObjects(id) {
  return {
    type: GET_OBJECTS,
    id,
  };
}

function getObjectsSuccess(data) {
  return {
    type: GET_OBJECTS_SUCCESS,
    data,
  };
}

function getObjectsError(error) {
  return {
    type: GET_OBJECTS_ERROR,
    data,
  };
}

const getObjectsEpic = (action$, store) = action$
  .ofType(GET_OBJECTS)
  .switchMap(action => Observable.ajax({
      url: `http://example.com?id=${action.id}`,
    })
    .map(response => getObjectsSuccess(response))
    .catch(error => getObjectsError(error))         
    .takeUntil(MY_STOPPING_ACTION)
  );
0

Source: https://habr.com/ru/post/1677157/


All Articles