Skip to content

Commit

Permalink
Add better response handling for updating existing message
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulJKim committed Oct 29, 2024
1 parent 6c50e93 commit b3f70ce
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
17 changes: 9 additions & 8 deletions assets/js/components/Dashboard/EditPaMessage/EditPaMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}}
/>
Expand Down
13 changes: 6 additions & 7 deletions assets/js/components/Dashboard/PaMessagesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -306,14 +306,13 @@ const PaMessageRow: ComponentType<PaMessageRowProps> = ({

const togglePaused = async (event: React.MouseEvent<HTMLDivElement>) => {
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);
}
};

Expand Down
11 changes: 11 additions & 0 deletions assets/js/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down

0 comments on commit b3f70ce

Please sign in to comment.