From 8234a410038c4644aed163411663304b2cd1fa9b Mon Sep 17 00:00:00 2001 From: Peter Beverloo Date: Fri, 21 Jun 2024 22:33:10 +0100 Subject: [PATCH] Teach server actions how to redirect the user, and how to refresh the page --- app/admin/components/FormGridSection.tsx | 12 +++++++++--- app/lib/serverAction.ts | 18 +++++++++++++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/app/admin/components/FormGridSection.tsx b/app/admin/components/FormGridSection.tsx index d61db80d..ca9dde1d 100644 --- a/app/admin/components/FormGridSection.tsx +++ b/app/admin/components/FormGridSection.tsx @@ -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'; @@ -60,15 +61,20 @@ export function FormGridSection(props: React.PropsWithChildren { 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); }); diff --git a/app/lib/serverAction.ts b/app/lib/serverAction.ts index 39fcabe0..381c623c 100644 --- a/app/lib/serverAction.ts +++ b/app/lib/serverAction.ts @@ -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 `` component & friends, but may be consumed by manual usage. + */ + [key: string]: any; } | { /**