Skip to content

Commit

Permalink
Teach server actions how to redirect the user, and how to refresh the…
Browse files Browse the repository at this point in the history
… page
  • Loading branch information
beverloo committed Jun 21, 2024
1 parent 4625691 commit 8234a41
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 9 additions & 3 deletions app/admin/components/FormGridSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { useState, useTransition } from 'react';

import { FormProvider, useForm } from '@proxy/react-hook-form-mui';
import { useRouter } from 'next/navigation';

import Alert from '@mui/material/Alert';
import Collapse from '@mui/material/Collapse';
Expand Down Expand Up @@ -60,15 +61,20 @@ export function FormGridSection(props: React.PropsWithChildren<FormGridSectionPr
// TODO: Convert DayJS values to something that can be read as a ZonedDateTime on the server.

const form = useForm();
const router = useRouter();

const handleSubmit = form.handleSubmit(async (data: unknown) => {
await startTransition(async () => {
const result = await action(data);
if (!!result.success)
if (!!result.success) {
form.reset({ /* fields */ }, { keepValues: true });

// TODO: Support `redirect` to automatically redirect the user to another page.
// TODO: Support `refresh` to automatically refresh using the Next.js router.
if (!!result.redirect)
router.push(result.redirect);

if (!!router.refresh)
router.refresh();
}

setState(result);
});
Expand Down
18 changes: 15 additions & 3 deletions app/lib/serverAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,21 @@ export type ServerActionResult = {
*/
success: true,

// TODO: Support `redirect` to automatically redirect the user to another page.
// TODO: Support `refresh` to automatically refresh using the Next.js router.
// TODO: Support arbitrary data payloads.
/**
* URL that the user should be redirected to now that this action has succeeded.
*/
redirect?: string;

/**
* Whether the page, and its entire state, should be refreshed.
*/
refresh?: boolean;

/**
* Arbitrary data that should be carried as part of the server action. Will not be consumed by
* the `<FormGridSection>` component & friends, but may be consumed by manual usage.
*/
[key: string]: any;

} | {
/**
Expand Down

0 comments on commit 8234a41

Please sign in to comment.