Skip to content

Instantly share code, notes, and snippets.

@longsangstan
Last active May 22, 2020 00:38
Show Gist options
  • Save longsangstan/2e0ffeee6ffbb5ae3971df91c9baf768 to your computer and use it in GitHub Desktop.
Save longsangstan/2e0ffeee6ffbb5ae3971df91c9baf768 to your computer and use it in GitHub Desktop.
react hook for post/put
import { useState } from "react";
import urljoin from "url-join";
const useSave = <T>(method: "post" | "put") => {
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState("");
const save = async (endpoint: string, body: T) => {
setError("");
setIsSaving(true);
try {
const response = await fetch(endpoint, {
method: method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`API request failed - ${response.status}`);
}
} catch (e) {
setError((e as Error).message);
setIsSaving(false);
return false;
}
setIsSaving(false);
return true;
};
return { isSaving, error, save };
};
export default useSave;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment