Client Component
"use client";
import { handleSubmit } from "@/actions/actions";
import React, { useActionState } from "react";
const Home = () => {
const initialState = {
message: null,
success: false,
};
const [state, action, isPending] = useActionState(handleSubmit, null); // Works fine with `null` but gives ts error overload matches with `initialState`
return (
<form
action={action}
className="h-screen w-full flex flex-col justify-center items-center gap-6"
>
<input
className="text-black"
name="title"
id="title"
placeholder="Title"
/>
{state?.message && state?.success ? (
<p className="text-green-500 font-bold">{state?.message}</p>
) : (
<p className="text-red-500 font-bold">{state?.message}</p>
)}
<button
className="bg-green-500 p-3 rounded-md disabled:bg-gray-500"
disabled={isPending}
>
{isPending ? "Adding" : "Add"}
</button>
</form>
);
};
export default Home;
Action
"use server";
export const handleSubmit = async (prevState: unknown, formData: FormData) => {
const title = formData.get("title") as string;
await new Promise((resolve) => setTimeout(resolve, 3000));
if (title.trim().length === 0) {
return { message: "Please Provide Valid Values", success: false };
}
if (title === "error") {
return { message: "Error occurred", success: false };
}
if (title === "success") {
return { message: "Success occurred", success: true };
}
};
Issues I’m Facing:
- Initial State Error:
When I pass the initialState object instead of null as the second argument useActionState, I get an error.
• Why does this happen?
• Is there a specific structure the initial state needs to follow? - Clearing State After Form Submission:
Once the form is submitted and I get a response (e.g., success or error message), I want the message to disappear after 3 seconds automatically. How can I implement this behavior cleanly within the component? - Any use cases for the prevState