S
Documentation

useSurvey — API Reference

Complete reference for the useSurvey hook — the headless engine that powers survey state, navigation, validation, and submission.

Import

import { useSurvey } from 'react-minimal-survey-builder';

Signature

function useSurvey(
  schema: SurveySchema,
  options?: SurveyOptions
): UseSurveyReturn;

Parameters

ParamTypeDescription
schemaSurveySchemaThe survey schema defining pages, questions, and settings.
optionsSurveyOptionsOptional callbacks, initial answers, and custom validators.

SurveyOptions

SurveyOptionstypescript
interface SurveyOptions {
  initialAnswers?: SurveyAnswers;
  onChange?: (answers: SurveyAnswers, questionId: string) => void;
  onSubmit?: (answers: SurveyAnswers) => void | Promise<void>;
  onValidate?: (errors: ValidationError[]) => void;
  onPageChange?: (pageIndex: number) => void;
  validators?: Record<string, (value: AnswerValue, question: Question, answers: SurveyAnswers) => string | null>;
}
initialAnswersSurveyAnswers

Pre-populate answers for edit mode or saved progress.

onChange(answers, questionId) => void

Fires on every answer change. Receives all answers and the changed question ID.

onSubmit(answers) => void | Promise<void>

Called on final submit after validation passes. Supports async.

onValidate(errors) => void

Called whenever validation runs. Receives all errors.

onPageChange(pageIndex) => void

Called when navigating to a different page.

validatorsRecord<string, fn>

Custom validator functions keyed by question ID. Return string (error) or null (valid).

Return Object

UseSurveyReturntypescript
interface UseSurveyReturn {
  // Survey data
  survey: SurveySchema;
  answers: SurveyAnswers;

  // Answer management
  setAnswer: (id: string, value: AnswerValue) => void;
  setAnswers: (answers: SurveyAnswers) => void;

  // Validation
  errors: ValidationError[];
  getError: (id: string) => string | undefined;
  isValid: boolean;
  validate: () => boolean;
  validateCurrentPage: () => boolean;

  // Visibility
  getVisibleQuestions: () => Question[];
  getPageQuestions: (pageIndex: number) => Question[];
  visiblePages: Page[];

  // Navigation
  currentPageIndex: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
  nextPage: () => boolean;
  prevPage: () => void;
  goToPage: (index: number) => boolean;

  // Submission
  submit: () => Promise<void>;
  isSubmitted: boolean;
  reset: () => void;

  // Progress
  progress: number; // 0–100
}

Return Properties Detail

survey

The parsed and validated survey schema.

answers

The current answers map. Keys are question IDs.

setAnswer(id, value)

Set a single answer. Triggers onChange and re-evaluates visibility.

setAnswers(answers)

Bulk-set answers. Merges with existing answers.

errors

Array of current ValidationError objects.

getError(id)

Returns the first error message for a question, or undefined.

isValid

True if there are no validation errors.

validate()

Validates the entire survey. Returns true if no errors.

validateCurrentPage()

Validates only the current page. Returns true if no errors.

getVisibleQuestions()

Returns visible questions for the current page (filtered by visibleIf).

getPageQuestions(index)

Returns visible questions for a specific page index.

visiblePages

Array of pages whose visibleIf conditions are met.

currentPageIndex

Zero-based index of the current page.

totalPages

Total number of pages in the schema.

hasNextPage / hasPrevPage

Boolean helpers for navigation button visibility.

nextPage()

Navigate forward. Validates current page first. Returns false if validation fails.

prevPage()

Navigate backward. No validation performed.

goToPage(index)

Jump to a specific page. Validates current page first.

submit()

Validate and submit. Calls onSubmit if valid. Async.

isSubmitted

True after successful submission.

reset()

Reset all answers, errors, and navigation to initial state.

progress

Completion percentage (0–100) based on answered visible questions.

Example

Full Exampletsx
const {
  answers, setAnswer,
  getVisibleQuestions, getError,
  nextPage, prevPage, submit,
  currentPageIndex, totalPages,
  progress, isSubmitted, reset,
} = useSurvey(schema, {
  initialAnswers: { name: 'Jane' },
  onSubmit: async (answers) => {
    await fetch('/api/survey', {
      method: 'POST',
      body: JSON.stringify(answers),
    });
  },
  onChange: (answers, id) => {
    console.log(`${id} changed:`, answers[id]);
  },
  validators: {
    email: (value) => {
      if (typeof value === 'string' && !value.includes('@')) {
        return 'Invalid email';
      }
      return null;
    },
  },
});