Next.js Discord

Discord Forum

useFormState combined with useFormStatus

Unanswered
Harlequin posted this in #help-forum
Open in Discord
HarlequinOP
"use client";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useEffect, useState } from "react";
import { useFormState, useFormStatus } from "react-dom";
import { createProduct } from "../../../_actions/products";
const initialState = {
  message: "",
};
export function CreateProductDialog() {
  const [isOpen, setIsOpen] = useState(false);
  const [state, formAction] = useFormState(createProduct, initialState);
  const { pending } = useFormStatus();
  useEffect(() => {
    console.log(state, pending);
  }, [state, pending]);
  return (
    <AlertDialog open={isOpen}>
      <AlertDialogTrigger asChild>
        <Button
          variant="outline"
          onClick={() => {
            setIsOpen(true);
          }}
        >
          New Product
        </Button>
      </AlertDialogTrigger>

      <AlertDialogContent>
        <form action={formAction}>
          <AlertDialogHeader>
            <AlertDialogTitle>Create a new product</AlertDialogTitle>
            <AlertDialogDescription>
              Users can buy that product then
            </AlertDialogDescription>
          </AlertDialogHeader>

          <Input type="text" name="name" placeholder="Name" required />
       ...

          <AlertDialogFooter>
            <AlertDialogAction asChild>
              <Button disabled={pending} type="submit">
                Create
              </Button>
            </AlertDialogAction>
          </AlertDialogFooter>
        </form>
      </AlertDialogContent>
    </AlertDialog>
  );
}
`
for some reason the pending state is not triggering, but why?

0 Replies