mirror of
https://github.com/CompassConnections/Compass.git
synced 2026-03-25 10:02:27 -04:00
66 lines
1.8 KiB
TypeScript
66 lines
1.8 KiB
TypeScript
import {OptionTableKey} from 'common/profiles/constants'
|
|
import {run} from 'common/supabase/utils'
|
|
import {useEffect} from 'react'
|
|
import {usePersistentInMemoryState} from 'web/hooks/use-persistent-in-memory-state'
|
|
import {useLocale} from 'web/lib/locale'
|
|
import {db} from 'web/lib/supabase/db'
|
|
|
|
export async function fetchChoices(label: OptionTableKey, locale: string) {
|
|
const choicesById: Record<string, string> = {}
|
|
const {data} = await run(
|
|
db
|
|
.from(label)
|
|
.select(
|
|
`
|
|
id,
|
|
name,
|
|
${label}_translations!left (
|
|
locale,
|
|
name
|
|
)
|
|
`,
|
|
)
|
|
.eq(`${label}_translations.locale`, locale)
|
|
.order('name', {ascending: true}),
|
|
)
|
|
|
|
data.forEach((row: any) => {
|
|
const translated = row[`${label}_translations`]?.[0]?.name ?? row.name
|
|
choicesById[row.id] = translated
|
|
})
|
|
|
|
return choicesById
|
|
}
|
|
|
|
export const useChoices = (label: OptionTableKey) => {
|
|
const [choices, setChoices] = usePersistentInMemoryState<Record<string, string>>(
|
|
{},
|
|
`${label}-choices`,
|
|
)
|
|
const {locale} = useLocale()
|
|
|
|
const refreshChoices = async () => {
|
|
try {
|
|
const results = await fetchChoices(label, locale)
|
|
setChoices(results)
|
|
} catch (err) {
|
|
console.error('Error fetching choices:', err)
|
|
return {}
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
// debug('Fetching choices in use effect...')
|
|
refreshChoices()
|
|
}, [locale])
|
|
|
|
return {choices, refreshChoices}
|
|
}
|
|
|
|
export const useAllChoices = () => {
|
|
const {choices: interests, refreshChoices: refreshInterests} = useChoices('interests')
|
|
const {choices: causes, refreshChoices: refreshCauses} = useChoices('causes')
|
|
const {choices: work, refreshChoices: refreshWork} = useChoices('work')
|
|
return {interests, causes, work, refreshInterests, refreshCauses, refreshWork}
|
|
}
|