Simple React Effect Hook that executes callback with axios CancelToken as argument. Request cancel will be performed as effect destruction.
Using npm
npm i react-axios-effect
Execute API effect with cancel token. Request will be cancelen on component unmount.
import * as React from "react"
import axios from "axios";
import { useAxiosEffect } from "react-axios-effect";
export const FunctionalComponent = () => {
const [ data, setData ] = React.useState();
useAxiosEffect(
/* effect that returns AxiosPromise */
(cancelToken) => axios
.get("https://example.com/api/v1/", { cancelToken })
.then((response) => setData(response.data))
/* dependencies */
[ setData ]
);
if (data === undefined) {
/* render placeholder for loading state */
return <span>Loading...</span>
}
/* render your component */
return <pre>{JSON.strinfigy(data)}</pre>;
};