Last active
August 14, 2022 01:53
-
-
Save eblind39/90229f3d9db69698f97729e0f7ead6b5 to your computer and use it in GitHub Desktop.
ReactJS & Typescript - try catch fetch
This file contains hidden or 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
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