Skip to main content

Function Signature

async function createMessage(
  prevState: MessagePrevState,
  formData: FormData
): Promise<MessagePrevState>
Source: src/lib/actions/message/createMessage.ts:21

Parameters

prevState
MessagePrevState
required
Previous state object returned from the last invocation. Used by React’s useActionState hook.
formData
FormData
required
Form data containing the message details

Return Value

MessagePrevState
object

Validation Schema

The function uses Zod for validation:
const messageSchema = z.object({
  content: z.string().min(1, "Content cannot be empty"),
  sendToPhone: z
    .string()
    .regex(/^8801\d{9}$/, "Invalid phone number format. Must be 8801XXXXXXXXX"),
  sendAfter: z
    .number()
    .min(1, "Send after is required and minimum after 1 day"),
});

Behavior

  1. Validation: Form data is validated against the Zod schema
  2. API Call: Makes a POST request to {BACKEND_URL}/messages/create-one
  3. Authentication: Uses Basic Auth with environment credentials
  4. Revalidation: Calls revalidatePath("/") on success to refresh the home page
  5. Error Handling: Returns structured error messages for validation, backend, or network errors

Usage Example

import { useActionState } from "react";
import createMessage from "@/lib/actions/message/createMessage";

function MessageForm() {
  const [state, formAction] = useActionState(createMessage, {});
  
  return (
    <form action={formAction}>
      <textarea name="content" placeholder="Message content" />
      <input name="sendToPhone" placeholder="8801XXXXXXXXX" />
      <input name="sendAfter" type="number" min="1" />
      <button type="submit">Create Message</button>
      {state.error && <p>{state.error}</p>}
      {state.success && <p>Message created!</p>}
    </form>
  );
}

Backend Endpoint

POST /messages/create-one Headers:
  • Authorization: Basic authentication
  • Content-Type: application/json
Body:
{
  "content": "Hello world",
  "sendToPhone": "8801234567890",
  "sendAfter": 7
}

Build docs developers (and LLMs) love