Skip to content

Instantly share code, notes, and snippets.

@eblind39
Last active August 14, 2022 01:53
Show Gist options
  • Save eblind39/90229f3d9db69698f97729e0f7ead6b5 to your computer and use it in GitHub Desktop.
Save eblind39/90229f3d9db69698f97729e0f7ead6b5 to your computer and use it in GitHub Desktop.
ReactJS & Typescript - try catch fetch
try {
setIsFetching(true)
const apiURL = `${API_URL}/authentication/signin`
const strBody: BodyInit = `{"email":"${email}","password":"${password}"}`
const response: Response = await fetch(apiURL, {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: strBody,
})
if (!response.ok) throw response
const data = await response.json()
} catch (err: unknown) {
if (err instanceof Response) {
const data = await err.json()
if (data.hasOwnProperty('message')) {
setIsOpenSnack(true)
setErrorMessage(data.message)
}
}
} finally {
setIsFetching(false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment