Skip to content

Instantly share code, notes, and snippets.

@ravisiyer
Last active February 14, 2024 15:39
Show Gist options
  • Save ravisiyer/5760479a3bb4d4c70fe3c12ec2d66835 to your computer and use it in GitHub Desktop.
Save ravisiyer/5760479a3bb4d4c70fe3c12ec2d66835 to your computer and use it in GitHub Desktop.
useAxiosGet custom hook for axios get requests only: version using controller.signal.aborted
//lines snipped
function App() {
const [posts, setPosts] = useState([]);
const [arePostsLoading, setArePostsLoading] = useState(true);
const [searchPosts, setSearchPosts] = useState("");
const {
data,
isLoading: isDataLoading,
axiosGetError,
} = useAxiosGet("http://localhost:3500/Posts");
useEffect(() => {
if (!isDataLoading) {
setPosts(data);
setArePostsLoading(false);
}
const cleanup = () => {
setPosts([]);
setArePostsLoading(true);
};
return cleanup;
}, [isDataLoading, data]);
return (
//lines snipped
<Route
index
element={
<Home
posts={
searchPosts.trim().length === 0
? posts
: posts.filter((post) => {
return (
post.title
.toLowerCase()
.includes(searchPosts.toLowerCase()) ||
post.body
.toLowerCase()
.includes(searchPosts.toLowerCase())
);
})
}
arePostsLoading={arePostsLoading}
axiosGetError={axiosGetError}
/>
}
/>
//lines snipped
import axios from "axios";
import { useState, useEffect } from "react";
const useAxiosGet = (url) => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [axiosGetError, setAxiosGetError] = useState("");
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
const getAxiosData = async () => {
try {
const res = await axios.get(url, {
signal: controller.signal,
});
setData(res.data);
setAxiosGetError("");
setIsLoading(false);
} catch (error) {
if (!controller.signal.aborted) {
setAxiosGetError(error.message);
setData([]);
setIsLoading(false);
}
}
};
const cleanup = () => {
controller.abort();
setData([]);
setAxiosGetError("");
setIsLoading(true);
};
getAxiosData();
return cleanup;
}, [url]);
return { data, isLoading, axiosGetError };
};
export default useAxiosGet;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment