Created
October 27, 2025 13:45
-
-
Save av1v3k/018b3b9faedfe66faed409d86c6c5800 to your computer and use it in GitHub Desktop.
useActionState() - starter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Product Form: | |
| ============ | |
| "use client" | |
| import { useActionState } from "react"; | |
| import { productAction } from "@/app/actions/product"; | |
| export default function ProductForm() { | |
| const initialState = { | |
| message: null, | |
| success: false | |
| } | |
| const [state, action, isPending] = useActionState(productAction, initialState); | |
| return ( | |
| <form action={action}> | |
| <input type="text" name="firstname"/> | |
| <button type="submit" disabled={isPending}>Submit</button> | |
| {state.message} | |
| </form> | |
| ) | |
| } | |
| Product Action: | |
| =============== | |
| "use server" | |
| export async function productAction(previousState, formData: FormData) { | |
| await new Promise((resolve) => setTimeout(resolve, 2000)); | |
| const data = { | |
| firstname: formData.get('firstname') as string | |
| } | |
| console.log(data); | |
| if(data.firstname == '') { | |
| return { | |
| message: 'Error, Firstname can\'t be empty', | |
| success: false | |
| } | |
| } | |
| return { | |
| message: 'Success ! submitted the form', | |
| success: true | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment