Increment Counter Example
In this example, we will create a simple counter that increments by one each time a button is clicked.
"use server";
import { createActionWithState } from 'better-react-server-actions';
import { z } from 'zod';
export const incrementCounter = createActionWithState({
stateSchema: z.object({
count: z.number().min(0),
}),
requestHandler: async ({ count }) => {
return {
count: count + 1,
}
}
});
"use client";
import { useActionState } from 'react';
import { incrementCounter } from './action';
export default function Page() {
const [state, action] = useActionState(incrementCounter, {
count: 0,
});
return (
<form action={action}>
<span>Count: {state.count}</span>
<button>
Increment
</button>
</form>
)
}