Last active
May 22, 2020 00:38
-
-
Save longsangstan/2e0ffeee6ffbb5ae3971df91c9baf768 to your computer and use it in GitHub Desktop.
react hook for post/put
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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