Skip to content

Commit

Permalink
Feat: add extra_properties type to FormStoreState type, on page reloa…
Browse files Browse the repository at this point in the history
…d set chosen radio inputs back to chosen input
  • Loading branch information
justiandevs committed Oct 23, 2024
1 parent 1769eba commit 2807880
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/components/ui/RadioGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react'
import { PublicQuestionSerializerDetail } from '@/services/client'
import { FieldErrors, FieldValues, UseFormRegister } from 'react-hook-form'
import { useTranslations } from 'next-intl'
import { useFormStore } from '@/store/form_store'

type RadioGroupProps = {
field: PublicQuestionSerializerDetail
Expand All @@ -11,9 +12,25 @@ type RadioGroupProps = {

export const RadioGroup = ({ field, register, errors }: RadioGroupProps) => {
const t = useTranslations('general.errors')
const { formState } = useFormStore()

const errorMessage = errors[field.key]?.message as string

// Check if the user has already answered a specific question.
// Returns true if an answer exists, otherwise returns false.
// This is used to determine if the 'defaultChecked' property of a radio input should be set.
const getDefaultValueRadioInput = (id: string, key: string) => {
const extraProperties = formState.extra_properties.filter(
(question) => question.id === id
)

if (typeof extraProperties[0].answer !== 'string') {
return extraProperties[0].answer.id === key
}

return false
}

return (
<fieldset aria-invalid={!!errorMessage}>
<legend>{field.meta.label}</legend>
Expand All @@ -38,6 +55,7 @@ export const RadioGroup = ({ field, register, errors }: RadioGroupProps) => {
id={`${field.key}-${key}`}
value={key}
aria-describedby={errorMessage ? `${field.key}-error` : undefined}
defaultChecked={getDefaultValueRadioInput(field.key, key)}
/>
<label htmlFor={`${field.key}-${key}`}>
{field.meta.values[key]}
Expand Down
13 changes: 12 additions & 1 deletion src/types/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@ type FormStoreState = {
email?: string | null
phone?: string | null
sharing_allowed?: boolean
extra_properties: object[]
extra_properties: Array<{
answer:
| {
id: string
label: string
info: string
}
| string
category_url: string
id: string
label: string
}>
}

type FormStore = {
Expand Down

0 comments on commit 2807880

Please sign in to comment.