L
L
lexstile2021-04-12 16:29:36
React
lexstile, 2021-04-12 16:29:36

How to write a universal method on axios that could cancel previous pending requests, but not all?

How to refine the solution so that the method call cancels its own previous call, but does not cancel other calls. Is it possible to somehow modify the universally current solution?
To avoid having to cancel each request separately.

For example:
- done in parallel, no response yet, two requests - request A and request B (http.get, http.post)
- then method A was called again => in this case, only request A
should be canceled , request B should continue to work EnrollmentPanel .jsx


useEffect(() => {
    const asyncEnrollment = async () => {
      const data = { userId, filter };
      await initialEnrollment(dispatch, data);
    };

    asyncEnrollment();
  }, [dispatch, userId, filter]);

initialEnrollment.js
export const initialEnrollment = async (dispatch, data = null) => {
  try {
    const callEnrollmentResult = await callEnrollment(data)
      .then((response) => get(response, 'data', null))
      .catch((error) => {
        const status = get(error, 'response.status', 1000);
        throwError(status);
      });

    console.log('callEnrollmentResult', callEnrollmentResult);
  } catch (error) {
    dispatch(
      setError({
        code: get(error, 'code', null),
        message: get(error, 'message', null),
      })
    );
  }
};

callEnrollment.js
export const callEnrollment = ({ userId, filter }) =>
  http.post(`${API_URL}.${METHODS.CALL_ENROLLMENT}`, { userId, filter }).then((response) => {
    console.log(METHODS.CALL_ENROLLMENT, response);
    return response;
  });

http.js
const cancelToken = axios.CancelToken;
const source = cancelToken.source();

export const http = axios.create({
  headers: {
    Authorization: `Bearer ${LOCATION_HREF}`,
  },
  cancelToken: source.token,
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2021-04-19
@lexstile

Create a cancelToken for a particular request (cancelToken.source()), pass it to each request, and keep track of whether the request itself has completed. If not, then cancel.
https://github.com/axios/axios#cancellation

const cancelToken = axios.CancelToken;

const usePost = () => {
  const source = useRef(null);

  return () => {
    if (source.current) {
      source.current.cancel();
    }

    source.current = cancelToken.source();
    const result = http.post(`${API_URL}.${METHODS.CALL_ENROLLMENT}`, { cancelToken, userId, filter });

    // ........

    result.finally(() => {
      // Обнуляем токен при завершении запроса
      source.current = null;
   });

    return result;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question