Skip to content

Instantly share code, notes, and snippets.

@KrzysztofLen
Last active May 24, 2022 20:14
Show Gist options
  • Save KrzysztofLen/74ca14f65af72d809d73b74b670fecf2 to your computer and use it in GitHub Desktop.
Save KrzysztofLen/74ca14f65af72d809d73b74b670fecf2 to your computer and use it in GitHub Desktop.
useRequest hook for handling Http calls
import { useState } from "react";
import axios, { AxiosError, AxiosRequestConfig } from "axios";
import React from "react";
interface Props {
url: string;
method: "post" | "put" | "get" | "delete";
body: AxiosRequestConfig<unknown> | undefined;
onSuccess: (data: unknown) => void;
}
export default ({
url,
method,
body,
onSuccess,
}: Props): { doRequest: () => Promise<void>; errors: JSX.Element | null } => {
const [errors, setErrors] = useState<JSX.Element | null>(null);
const doRequest = async () => {
try {
setErrors(null);
const response = await axios[method](url, body);
if (onSuccess) {
onSuccess(response.data);
}
return response.data;
} catch (error: unknown | AxiosError) {
if (axios.isAxiosError(error)) {
setErrors(
<div className='alert alert-danger'>
<h4>Ooops ....</h4>
<ul className='my-0'>
<li>{error.message}</li>
</ul>
</div>
);
} else {
console.log(error);
}
}
};
return { doRequest, errors };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment