Skip to main content

State Types

State types are used with Next.js server actions and React’s useActionState hook to manage form submission states. These types follow a consistent pattern for handling success and error states.

MessagePrevState

State type for message creation and update operations.

Type Definition

interface MessagePrevState {
  success?: boolean;
  error?: string;
}

Properties

success
boolean
Indicates whether the message operation completed successfully.
  • true - Message was created/updated successfully
  • undefined - Operation hasn’t completed or failed
error
string
Error message if the operation failed. Contains detailed information about what went wrong.

Usage

Used with the createMessage server action in src/lib/actions/message/createMessage.ts:21-24:
import { MessagePrevState } from './types';

export default async function createMessage(
  prevState: MessagePrevState,
  formData: FormData
): Promise<MessagePrevState> {
  try {
    // Validation and processing
    const parsedData = messageSchema.safeParse({
      content: formData.get("content"),
      sendToPhone: formData.get("sendToPhone"),
      sendAfter: Number(formData.get("sendAfter")),
    });

    if (!parsedData.success) {
      return {
        error: parsedData.error.errors.map((err) => err.message).join(", "),
      };
    }

    // API call...
    return { success: true };
  } catch (error) {
    return {
      error: error instanceof Error ? error.message : "Something went wrong",
    };
  }
}

PersonPrevState

State type for person creation and update operations.

Type Definition

interface PersonPrevState {
  success?: boolean;
  error?: string;
}

Properties

success
boolean
Indicates whether the person operation completed successfully.
  • true - Person was created/updated successfully
  • undefined - Operation hasn’t completed or failed
error
string
Error message if the operation failed.

Usage

Used with the createPerson server action in src/lib/actions/people/createPerson.ts:18-21:
import { PersonPrevState } from './types';

export default async function createPerson(
  prevState: PersonPrevState,
  formData: FormData
): Promise<PersonPrevState> {
  try {
    const parsedData = personSchema.safeParse({
      name: formData.get("name"),
      phone: formData.get("phone"),
    });

    if (!parsedData.success) {
      return {
        error: parsedData.error.errors.map((err) => err.message).join(", "),
      };
    }

    // API call...
    return { success: true };
  } catch (error) {
    return {
      error: error instanceof Error ? error.message : "Something went wrong",
    };
  }
}

RescheduleState

State type for the message rescheduling operation.

Type Definition

interface RescheduleState {
  success: boolean;
  error?: string;
}

Properties

success
boolean
required
Indicates whether the reschedule operation completed successfully.
Unlike other state types, success is required (not optional) in RescheduleState.
  • true - Messages were rescheduled successfully
  • false - Reschedule operation failed
error
string
Error message if the operation failed. Only present when success is false.Possible values:
  • Error message from caught exception
  • "Unknown error" - Fallback for non-Error exceptions

Key Difference

Important: RescheduleState.success is required, while MessagePrevState.success and PersonPrevState.success are optional.This means a RescheduleState always has an explicit success value (true or false), whereas other state types use undefined to indicate pending/initial state.

Usage

Used with the reschedule server action in src/lib/actions/reschedule/reschedule.ts:10:
import { RescheduleState } from './types';

export default async function reschedule(): Promise<RescheduleState> {
  try {
    const response = await fetch(
      `${process.env.BACKEND_URL}/messages/reschedule`,
      {
        method: "GET",
        headers: {
          Authorization: `Basic ${credentials}`,
        },
      }
    );
    
    if (!response.ok) {
      return { success: false };
    }
    
    revalidatePath("/");
    return { success: true };
  } catch (e) {
    return { 
      success: false, 
      error: e instanceof Error ? e.message : "Unknown error" 
    };
  }
}

State Pattern Overview

All state types follow a consistent pattern for error handling in Next.js server actions:

Success/Error Pattern

  1. Initial State: Empty object or { success: false }
  2. Success: Returns { success: true }
  3. Validation Error: Returns { error: "validation message" }
  4. API Error: Returns { error: "Backend Error: ..." }
  5. Exception: Returns { error: error.message }

Best Practices

function FormComponent() {
  const [state, formAction] = useActionState(createMessage, {});

  // Check error first
  if (state.error) {
    return <ErrorMessage message={state.error} />;
  }

  // Then check success
  if (state.success) {
    return <SuccessMessage />;
  }

  // Default: show form
  return <form action={formAction}>...</form>;
}
  • Message - Used in message operations
  • People - Used in person operations

Build docs developers (and LLMs) love