From b3f70ce39b91b82232378a216eda91f0499b4fd9 Mon Sep 17 00:00:00 2001 From: Kim Date: Tue, 29 Oct 2024 13:30:23 -0400 Subject: [PATCH] Add better response handling for updating existing message --- .../Dashboard/EditPaMessage/EditPaMessage.tsx | 17 +++++++++-------- .../js/components/Dashboard/PaMessagesPage.tsx | 13 ++++++------- assets/js/utils/api.ts | 11 +++++++++++ 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/assets/js/components/Dashboard/EditPaMessage/EditPaMessage.tsx b/assets/js/components/Dashboard/EditPaMessage/EditPaMessage.tsx index dc842a64..cc343ffe 100644 --- a/assets/js/components/Dashboard/EditPaMessage/EditPaMessage.tsx +++ b/assets/js/components/Dashboard/EditPaMessage/EditPaMessage.tsx @@ -107,16 +107,17 @@ const EditPaMessage = ({ paMessage, alert }: Props) => { defaultAudioState={AudioPreview.Reviewed} paused={paMessage.paused} onSubmit={async (data) => { - const result = await updateExistingPaMessage(paMessage.id, data); - - if (result.status === 200) { + try { + await updateExistingPaMessage(paMessage.id, data); mutate(`/api/pa-messages/${paMessage.id}`); navigate("/pa-messages"); - } else if (result.status === 422) { - setErrorMessage("Correct the following errors:"); - setErrors(Object.keys(result.body.errors)); - } else { - setErrorMessage("Something went wrong. Please try again."); + } catch (error) { + if (Array.isArray(error)) { + setErrorMessage("Correct the following errors:"); + setErrors(error); + } else { + setErrorMessage((error as Error).message); + } } }} /> diff --git a/assets/js/components/Dashboard/PaMessagesPage.tsx b/assets/js/components/Dashboard/PaMessagesPage.tsx index a3fe80c0..191254ee 100644 --- a/assets/js/components/Dashboard/PaMessagesPage.tsx +++ b/assets/js/components/Dashboard/PaMessagesPage.tsx @@ -306,14 +306,13 @@ const PaMessageRow: ComponentType = ({ const togglePaused = async (event: React.MouseEvent) => { event.stopPropagation(); - const result = await updateExistingPaMessage(paMessage.id, { - paused: !paMessage.paused, - } as UpdatePaMessageBody); - - if (result.status === 200) { + try { + await updateExistingPaMessage(paMessage.id, { + paused: !paMessage.paused, + } as UpdatePaMessageBody); updatePaMessage({ ...paMessage, paused: !paMessage.paused }); - } else { - setErrorMessage("Something went wrong. Please try again."); + } catch (error) { + setErrorMessage((error as Error).message); } }; diff --git a/assets/js/utils/api.ts b/assets/js/utils/api.ts index 950eef3a..a55d1d45 100644 --- a/assets/js/utils/api.ts +++ b/assets/js/utils/api.ts @@ -149,6 +149,17 @@ export const updateExistingPaMessage = async ( body: JSON.stringify(updates), }); + if (response.status === 422) { + const body = await response.json(); + const error = Object.keys(body.errors); + + throw error; + } else if (!response.ok) { + const error = new Error(`Error: ${response.status} ${response.statusText}`); + + throw error; + } + return { status: response.status, body: await response.json(),