Skip to content

Commit

Permalink
handle error when saving a message
Browse files Browse the repository at this point in the history
It preserves the record text
  • Loading branch information
siavol committed Sep 8, 2024
1 parent ada2468 commit 09b6c6d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
30 changes: 25 additions & 5 deletions src/components/record/record-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,35 @@ import {
JournalRecord,
} from '../../services/journal-repository'

function getSavingError(error: unknown): Error {
if (error instanceof Error) {
return error
}
return new Error('Unknown saving error', { cause: error })
}

export type SaveRecordProblem = {
recordText: string
error: Error
}

export async function newRecordAction(
args: ActionFunctionArgs
): Promise<Response> {
const values = Object.fromEntries(await args.request.formData())

): Promise<Response | SaveRecordProblem> {
const config = loadConfig()
await createRecord(values.content.toString(), config)
const values = Object.fromEntries(await args.request.formData())
const recordText = values.content.toString()

return redirect('/')
try {
await createRecord(recordText, config)
return redirect('/')
} catch (err) {
console.error('Failed to save a record', err)
return {
recordText,
error: getSavingError(err),
}
}
}

export async function recordsLoader(): Promise<JournalRecord[]> {
Expand Down
20 changes: 17 additions & 3 deletions src/components/record/record-new.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
import { Button, Container, Stack, TextField, Typography } from '@mui/material'
import {
Alert,
Button,
Container,
Stack,
TextField,
Typography,
} from '@mui/material'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Form } from 'react-router-dom'
import { Form, useActionData } from 'react-router-dom'
import { SaveRecordProblem } from './record-actions'

const RecordNew: React.FunctionComponent = () => {
const [content, setContent] = useState('')
const savingProblem = useActionData() as SaveRecordProblem | undefined
const [content, setContent] = useState(savingProblem?.recordText || '')
const { t } = useTranslation(['record', 'general'])

const errorAlert = savingProblem ? (
<Alert severity="error">Saving failed: {savingProblem.error.message}</Alert>
) : null

return (
<Container>
{errorAlert}
<Typography variant="h4">{t('New Record')}</Typography>
<Form method="post">
<Stack>
Expand Down

0 comments on commit 09b6c6d

Please sign in to comment.