Overview
The useEncuestasStore manages surveys (encuestas) with support for multiple question types, user responses, and statistical analysis. It handles survey creation, submission, and results visualization.
State Properties
Array of surveys
id: string - Unique identifier
titulo: string - Survey title
descripcion: string | null - Survey description
tipo: “abierta” | “calificacion” | “opcion_multiple” - Question type
opciones: any[] - Question options/configuration
activa: boolean - Whether survey is active
administrador_id: string - ID of admin who created it
created_at: string - Creation timestamp
updated_at: string - Last update timestamp
Currently selected/viewed survey
Array of survey responses Show RespuestaEncuesta Type
id: string - Unique identifier
encuesta_id: string - Associated survey ID
usuario_id: string - User who submitted response
respuesta: Record<string, any> - Response data
created_at: string - Submission timestamp
Loading state for async operations
Error message from last failed operation
Actions
fetchEncuestas
Fetches surveys with optional active filter.
const result = await encuestasStore . fetchEncuestas ( soloActivas )
If true, returns only active surveys
return
Promise<{ success: boolean; data?: Encuesta[]; error?: string }>
Result object with surveys array
fetchEncuesta
Fetches a single survey by ID.
const result = await encuestasStore . fetchEncuesta ( id )
return
Promise<{ success: boolean; data?: Encuesta; error?: string }>
Result object with survey data
crearEncuesta
Creates a new survey (admin only).
const result = await encuestasStore . crearEncuesta ( encuesta )
Survey data tipo
'abierta' | 'calificacion' | 'opcion_multiple'
required
Question type
Question options/configuration (format depends on tipo)
Admin user ID who creates the survey
return
Promise<{ success: boolean; data?: Encuesta; error?: string }>
Result object with created survey data
Behavior:
Verifies session validity before creation
Prepends new survey to local encuestas array
actualizarEncuesta
Updates an existing survey.
const result = await encuestasStore . actualizarEncuesta ( id , updates )
updates
Partial<InsertEncuesta>
required
Fields to update
return
Promise<{ success: boolean; data?: Encuesta; error?: string }>
Result object with updated survey data
Behavior:
Automatically updates updated_at timestamp
Updates survey in local encuestas array if present
eliminarEncuesta
Deletes a survey.
const result = await encuestasStore . eliminarEncuesta ( id )
return
Promise<{ success: boolean; error?: string }>
Result object indicating success or failure
responderEncuesta
Submits a user’s response to a survey.
const result = await encuestasStore . responderEncuesta ( encuestaId , respuesta )
respuesta
Record<string, any>
required
Response data (format depends on survey type)
return
Promise<{ success: boolean; data?: RespuestaEncuesta; error?: string }>
Result object with submission data
Behavior:
Requires authenticated user
Checks if user has already responded (prevents duplicates)
Throws error if user already submitted response
Automatically adds usuario_id from auth store
fetchRespuestasEncuesta
Fetches all responses for a specific survey.
const result = await encuestasStore . fetchRespuestasEncuesta ( encuestaId )
return
Promise<{ success: boolean; data?: RespuestaEncuesta[]; error?: string }>
Result object with responses array
verificarYaRespondio
Checks if current user has already responded to a survey.
const yaRespondio = await encuestasStore . verificarYaRespondio ( encuestaId )
True if user has already responded, false otherwise
obtenerRespuestaUsuario
Retrieves the current user’s response for a survey.
const respuesta = await encuestasStore . obtenerRespuestaUsuario ( encuestaId )
return
Promise<Record<string, any> | null>
User’s response data or null if not found
obtenerEstadisticas
Calculates and returns statistics for survey responses.
const result = await encuestasStore . obtenerEstadisticas ( encuestaId )
Statistics object with format depending on survey type Show Return formats by survey type
For multiple choice with multiple questions: {
success : boolean ,
tipo : "multiple_preguntas" ,
data : Array <{
pregunta : string ,
estadisticas : Record < string , number >,
total : number
}>,
total : number
}
For open-ended questions: {
success : boolean ,
tipo : "abierta" ,
data : Array <{
respuesta : string ,
fecha : string
}>,
total : number
}
For rating and simple multiple choice: {
success : boolean ,
data : Record < string , number > , // option -> count
total : number
}
Features:
Automatically detects survey type from database
Processes responses differently based on question type
Supports complex multi-question surveys
Returns aggregated counts for multiple choice
Returns full text responses for open-ended questions
Usage Examples
Fetch Active Surveys
Submit Survey Response
View Statistics
Create Survey (Admin)
< script setup >
import { useEncuestasStore } from '@/stores/encuestas.store'
import { onMounted } from 'vue'
const encuestasStore = useEncuestasStore ()
onMounted ( async () => {
// Fetch only active surveys
await encuestasStore . fetchEncuestas ( true )
console . log ( 'Encuestas activas:' , encuestasStore . encuestas . length )
})
</ script >
< script setup >
import { useEncuestasStore } from '@/stores/encuestas.store'
import { ref } from 'vue'
const encuestasStore = useEncuestasStore ()
const encuestaId = ref ( 'survey-id' )
async function enviarRespuesta () {
// Check if already responded
const yaRespondio = await encuestasStore . verificarYaRespondio ( encuestaId . value )
if ( yaRespondio ) {
alert ( 'Ya has respondido esta encuesta' )
return
}
// Submit response
const result = await encuestasStore . responderEncuesta (
encuestaId . value ,
{
respuestaLibre: [ 'Opción A' , 'Opción B' ], // For multiple choice
// OR
calificacion: 5 , // For rating
// OR
respuestaLibre: 'Texto de respuesta' // For open-ended
}
)
if ( result . success ) {
console . log ( 'Respuesta enviada' )
} else {
console . error ( 'Error:' , result . error )
}
}
</ script >
< script setup >
import { useEncuestasStore } from '@/stores/encuestas.store'
import { ref , onMounted } from 'vue'
const encuestasStore = useEncuestasStore ()
const encuestaId = ref ( 'survey-id' )
const estadisticas = ref ( null )
onMounted ( async () => {
const result = await encuestasStore . obtenerEstadisticas ( encuestaId . value )
if ( result . success ) {
estadisticas . value = result
if ( result . tipo === 'multiple_preguntas' ) {
// Handle multi-question statistics
result . data . forEach (( pregunta ) => {
console . log ( `Pregunta: ${ pregunta . pregunta } ` )
console . log ( 'Respuestas:' , pregunta . estadisticas )
})
} else if ( result . tipo === 'abierta' ) {
// Handle open-ended responses
console . log ( 'Respuestas abiertas:' , result . data . length )
} else {
// Handle simple statistics
console . log ( 'Estadísticas:' , result . data )
}
}
})
</ script >
< script setup >
import { useEncuestasStore } from '@/stores/encuestas.store'
import { useAuthStore } from '@/stores/auth.store'
const encuestasStore = useEncuestasStore ()
const authStore = useAuthStore ()
async function crearEncuestaMultiple () {
const result = await encuestasStore . crearEncuesta ({
titulo: '¿Cómo calificarías nuestros servicios?' ,
descripcion: 'Ayúdanos a mejorar' ,
tipo: 'calificacion' ,
opciones: [ 1 , 2 , 3 , 4 , 5 ],
activa: true ,
administrador_id: authStore . user ! . id
})
if ( result . success ) {
console . log ( 'Encuesta creada:' , result . data ?. id )
}
}
async function crearEncuestaAbierta () {
const result = await encuestasStore . crearEncuesta ({
titulo: '¿Qué mejoras sugieres para tu barrio?' ,
descripcion: null ,
tipo: 'abierta' ,
opciones: [],
activa: true ,
administrador_id: authStore . user ! . id
})
}
</ script >
Survey Types
Supported Survey Types:
abierta (Open-ended): Users provide free-text responses
calificacion (Rating): Users select a numeric rating (e.g., 1-5 stars)
opcion_multiple (Multiple choice): Users select from predefined options
Can have single or multiple questions
Supports complex multi-question format with pregunta property
Users can only respond to each survey once. The store automatically prevents duplicate submissions by checking existing responses before allowing submission.
Notes
Use verificarYaRespondio() before displaying survey forms to show appropriate UI (e.g., “You’ve already completed this survey”).
The obtenerEstadisticas() action intelligently formats results based on survey type, making it easy to render appropriate visualizations (bar charts for multiple choice, lists for open-ended, etc.).