Skip to main content

Function Signature

async function updateMessage(
  prevState: MessagePrevState,
  formData: FormData
): Promise<MessagePrevState>
Source: src/lib/actions/message/updateMessage.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 to update

Return Value

MessagePrevState
object

Validation Schema

The function uses Zod for validation:
const messageSchema = z.object({
  id: z.string().min(1, "ID is required"),
  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(0, "Send after is required and minimum after 0 day"),
});

Behavior

  1. Validation: Form data is validated against the Zod schema
  2. API Call: Makes a POST request to {BACKEND_URL}/messages/update-one/{id}
  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 updateMessage from "@/lib/actions/message/updateMessage";

function EditMessageForm({ messageId }: { messageId: string }) {
  const [state, formAction] = useActionState(updateMessage, {});
  
  return (
    <form action={formAction}>
      <input type="hidden" name="id" value={messageId} />
      <textarea name="content" placeholder="Message content" />
      <input name="sendToPhone" placeholder="8801XXXXXXXXX" />
      <input name="sendAfter" type="number" min="0" />
      <button type="submit">Update Message</button>
      {state.error && <p>{state.error}</p>}
      {state.success && <p>Message updated!</p>}
    </form>
  );
}

Backend Endpoint

POST /messages/update-one/:id Headers:
  • Authorization: Basic authentication
  • Content-Type: application/json
Body:
{
  "id": "message-123",
  "content": "Updated message",
  "sendToPhone": "8801234567890",
  "sendAfter": 3
}

Differences from createMessage

  • ID Required: Must include the message ID to identify which message to update
  • sendAfter Minimum: Allows 0 days (vs. 1 day minimum for create)
  • Endpoint: Uses /update-one/:id instead of /create-one

Build docs developers (and LLMs) love