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
| Param | Type | Description |
|---|---|---|
schema | SurveySchema | The survey schema defining pages, questions, and settings. |
options | SurveyOptions | Optional callbacks, initial answers, and custom validators. |
SurveyOptions
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>;
}initialAnswersSurveyAnswersPre-populate answers for edit mode or saved progress.
onChange(answers, questionId) => voidFires 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) => voidCalled whenever validation runs. Receives all errors.
onPageChange(pageIndex) => voidCalled when navigating to a different page.
validatorsRecord<string, fn>Custom validator functions keyed by question ID. Return string (error) or null (valid).
Return Object
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
surveyThe parsed and validated survey schema.
answersThe 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.
errorsArray of current ValidationError objects.
getError(id)Returns the first error message for a question, or undefined.
isValidTrue 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.
visiblePagesArray of pages whose visibleIf conditions are met.
currentPageIndexZero-based index of the current page.
totalPagesTotal number of pages in the schema.
hasNextPage / hasPrevPageBoolean 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.
isSubmittedTrue after successful submission.
reset()Reset all answers, errors, and navigation to initial state.
progressCompletion percentage (0–100) based on answered visible questions.
Example
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;
},
},
});