Skip to content

Commit

Permalink
created useAxios hook
Browse files Browse the repository at this point in the history
  • Loading branch information
0xOmarAdel committed Feb 21, 2024
1 parent 7ba32e1 commit e428650
Show file tree
Hide file tree
Showing 4 changed files with 202 additions and 3 deletions.
144 changes: 142 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hookverse",
"version": "1.2.2",
"version": "1.3.2",
"description": "",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down Expand Up @@ -34,5 +34,9 @@
"peerDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"dependencies": {
"axios": "^1.6.7",
"query-string": "^8.2.0"
}
}
44 changes: 44 additions & 0 deletions src/hooks/useAxios.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useState, useCallback, useMemo } from "react";
import axios from "axios";
import queryString from "query-string";
import UseAxiosProps from "../types/UseAxiosProps.types";

const useAxios = ({
url,
method = "GET",
headers,
body,
searchParams,
}: UseAxiosProps) => {
const [data, setData] = useState<any | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);

const memoizedSearchParams = useMemo(() => {
return queryString.parse(searchParams || "");
}, [searchParams]);

const runAxios = useCallback(async () => {
try {
setLoading(true);

const response = await axios({
method,
url,
data: body,
params: memoizedSearchParams,
headers,
});

setData(response.data);
} catch (error) {
setError(!!error);
} finally {
setLoading(false);
}
}, [method, url, headers, body,memoizedSearchParams]);

return { runAxios, data, loading, error };
};

export default useAxios;
11 changes: 11 additions & 0 deletions src/types/UseAxiosProps.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { AxiosRequestConfig } from "axios";

type UseAxiosProps = {
url: string;
method?: string;
headers?: AxiosRequestConfig["headers"];
body?: any;
searchParams?: string | null;
};

export default UseAxiosProps;

0 comments on commit e428650

Please sign in to comment.