I
I
Ivan Derbenchenko2021-08-25 17:08:53
React
Ivan Derbenchenko, 2021-08-25 17:08:53

How to implement axios request interrupt from Redux-saga?

Hello everyone, for a long time I can not find a solution, I ask for help from the experienced!
June!) The
devil pulled me on the instructions of PM connected redux-saga. After reading several articles and watching a couple of videos, I also connected the connected-react-router in general, everything suits me, but there is one but!
Tell me how you can interrupt the request to RestAPI made using axios?
I have a single Api class that stores all methods for accessing the database:

class Api {
   
    constructor() {
        this.client = axios.create();
        this.token = localStorage.getItem('access_token');
        this.refreshToken = localStorage.getItem('refresh_token');

        this.refreshRequest = null;

        this.client.defaults.baseURL = "http://127.0.0.1:8000/api/v1";
        this.client.interceptors.request.use(
            (config) => {
                // ...code
        );

        this.client.interceptors.response.use(
            (r) => r,
            async (error) => {
                // ... code
            }
        );
    }
   // пошли всевозможные методы
    async checkClient(id, set) {...}

    async getProfile(id) {...}

    async editProfile(id, data) {...}
   // ...

In the saga, I have a request that I don’t know how to stop when the component is unmounted
// ... это то что я пробовал
function* fetchAllClients(token) {
    const response = yield Api.getAllClients(token);
    yield put(load_clients_all_done(response.data));
    console.log('push')
}

export function* loadclientsPage() {
    const cancelSource = axios.CancelToken.source()
    try {
        yield all([
            call(fetchAllClients, cancelSource.token),
            /// ...
        ]);
    } catch(e){
        yield put(load_clients_all_fail(e))
    }
    finally {
        if (yield cancelled()) {
            yield cancelSource.cancel()
        }
    }
}

export default function* clientsPageSagas() {
    yield takeEvery(LOAD_CLIENTS_ALL, loadclientsPage);

};


There was also a hint from the github forum
async getAllClients() {
        const source = CancelToken.source()
        const request = await this.client.get("/client/", {cancelToken: source.token});
        request[CANCEL] = () => source.cancel();
        return request;
    }


But to my regret, I still did not understand how to do the cancellation itself ....

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question