From 0bfff6948ec5d29e57b5436afa558bdbaff1a143 Mon Sep 17 00:00:00 2001 From: bholmesdev Date: Mon, 20 May 2024 17:29:42 -0400 Subject: [PATCH] chore: changeset --- .changeset/gentle-windows-enjoy.md | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .changeset/gentle-windows-enjoy.md diff --git a/.changeset/gentle-windows-enjoy.md b/.changeset/gentle-windows-enjoy.md new file mode 100644 index 000000000000..ac9b1ccd92e9 --- /dev/null +++ b/.changeset/gentle-windows-enjoy.md @@ -0,0 +1,46 @@ +--- +"@astrojs/react": minor +"astro": minor +--- + +Add support for [the React 19 `useActionState()` hook](https://react.dev/reference/react/useActionState) when using Astro Actions. This introduces progressive enhancement when calling an Action with the `withState()` utility. + +This example calls a `like` action that accepts a `postId` and returns the number of likes. Pass this action to the `experimental_withState()` function to apply progressive enhancement info, and apply to `useActionState()` to track the result: + +```tsx +import { actions } from 'astro:actions'; +import { experimental_withState } from '@astrojs/react/actions'; + +export function Like({ postId }: { postId: string }) { + const [state, action, pending] = useActionState( + experimental_withState(actions.like), + 0, // initial likes + ); + + return ( +
+ + +
+ ); +} +``` + +You can also access the state stored by `useActionState()` from your action `handler`. Call `experimental_getActionState()` with the API context, and optionally apply a type to the result: + +```ts +import { defineAction, z } from 'astro:actions'; +import { experimental_getActionState } from '@astrojs/react/actions'; + +export const server = { + like: defineAction({ + input: z.object({ + postId: z.string(), + }), + handler: async ({ postId }, ctx) => { + const currentLikes = experimental_getActionState(ctx); + // write to database + return currentLikes + 1; + } + }) +}