react-hooks-introduction icon indicating copy to clipboard operation
react-hooks-introduction copied to clipboard

useDataApi: Is it worth to add axios.CancelToken ?

Open albertly opened this issue 4 years ago • 0 comments

Something like this?

 useEffect(() => {
    const cancelTokenSource = axios.CancelToken.source();

    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' });

      try {
        const result = await await axios(url, {
            cancelToken: cancelTokenSource.token,
          });

        if (!axios.isCancel()) {
          dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
        }
      } catch (error) {
        if (!axios.isCancel(error)) {
          dispatch({ type: 'FETCH_FAILURE' });
        }
      }
    };

    fetchData();

    return () => {
      cancelTokenSource.cancel();
    };
  }, [url]);

albertly avatar Jan 26 '21 16:01 albertly