mirror of
https://github.com/withastro/astro.git
synced 2025-03-10 23:01:26 -05:00
feat(ex): Like with useActionState
This commit is contained in:
parent
c36d28dffd
commit
29a207ce5f
2 changed files with 14 additions and 11 deletions
|
@ -5,8 +5,10 @@ import { getCollection } from 'astro:content';
|
|||
export const server = {
|
||||
blog: {
|
||||
like: defineAction({
|
||||
input: z.object({ postId: z.string() }),
|
||||
handler: async ({ postId }) => {
|
||||
accept: 'form',
|
||||
input: z.object({ postId: z.string(), state: z.string().transform(t => JSON.parse(t)) }),
|
||||
handler: async ({ postId, state }) => {
|
||||
console.log('state', state);
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
|
||||
const { likes } = await db
|
||||
|
|
|
@ -1,22 +1,23 @@
|
|||
import { actions } from 'astro:actions';
|
||||
import { useState } from 'react';
|
||||
import { useActionState } from 'react';
|
||||
import { withState } from '@astrojs/react/actions';
|
||||
|
||||
export function Like({ postId, initial }: { postId: string; initial: number }) {
|
||||
const [likes, setLikes] = useState(initial);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [state, action, pending] = useActionState(
|
||||
withState(actions.blog.like),
|
||||
initial,
|
||||
);
|
||||
|
||||
return (
|
||||
<form action={action}>
|
||||
<input type="hidden" name="postId" value={postId} />
|
||||
<button
|
||||
aria-label="Like"
|
||||
disabled={pending}
|
||||
onClick={async () => {
|
||||
setPending(true);
|
||||
setLikes(await actions.blog.like({ postId }));
|
||||
setPending(false);
|
||||
}}
|
||||
type="submit"
|
||||
>
|
||||
{likes} ❤️
|
||||
{state} ❤️
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue