1+ import { debug } from 'common/logger'
12import { OptionTableKey } from 'common/profiles/constants'
23import { run } from 'common/supabase/utils'
3- import { useEffect } from 'react'
4+ import { createContext , ReactNode , useContext , useEffect } from 'react'
45import { usePersistentInMemoryState } from 'web/hooks/use-persistent-in-memory-state'
56import { useLocale } from 'web/lib/locale'
67import { db } from 'web/lib/supabase/db'
78
9+ const ChoicesContext = createContext < UseAllChoices | null > ( null )
10+
11+ export const ChoicesProvider = ( { children} : { children : ReactNode } ) => {
12+ const choices = useAllChoices ( )
13+ return < ChoicesContext . Provider value = { choices } > { children } </ ChoicesContext . Provider >
14+ }
15+
16+ export const useChoicesContext = ( ) => {
17+ const ctx = useContext ( ChoicesContext )
18+ if ( ! ctx ) throw new Error ( 'useChoicesContext must be used within a ChoicesProvider' )
19+ return ctx
20+ }
21+
822export async function fetchChoices ( label : OptionTableKey , locale : string ) {
23+ debug ( 'Fetching choices for' , label )
924 const choicesById : Record < string , string > = { }
1025 const { data} = await run (
1126 db
@@ -32,32 +47,39 @@ export async function fetchChoices(label: OptionTableKey, locale: string) {
3247 return choicesById
3348}
3449
35- export const useChoices = ( label : OptionTableKey ) => {
50+ const useChoices = ( label : OptionTableKey ) => {
3651 const [ choices , setChoices ] = usePersistentInMemoryState < Record < string , string > > (
3752 { } ,
3853 `${ label } -choices` ,
3954 )
4055 const { locale} = useLocale ( )
4156
4257 const refreshChoices = async ( ) => {
43- try {
44- const results = await fetchChoices ( label , locale )
45- setChoices ( results )
46- } catch ( err ) {
47- console . error ( 'Error fetching choices:' , err )
48- return { }
49- }
58+ fetchChoices ( label , locale )
59+ . then ( setChoices )
60+ . catch ( ( err ) => {
61+ console . error ( 'Error fetching choices:' , err ?. message ?? err )
62+ return { }
63+ } )
5064 }
5165
5266 useEffect ( ( ) => {
53- // debug('Fetching choices in use effect...')
5467 refreshChoices ( )
5568 } , [ locale ] )
5669
5770 return { choices, refreshChoices}
5871}
5972
60- export const useAllChoices = ( ) => {
73+ export type UseAllChoices = {
74+ interests : Record < string , string >
75+ causes : Record < string , string >
76+ work : Record < string , string >
77+ refreshInterests : ( ) => void
78+ refreshCauses : ( ) => void
79+ refreshWork : ( ) => void
80+ }
81+
82+ const useAllChoices = ( ) => {
6183 const { choices : interests , refreshChoices : refreshInterests } = useChoices ( 'interests' )
6284 const { choices : causes , refreshChoices : refreshCauses } = useChoices ( 'causes' )
6385 const { choices : work , refreshChoices : refreshWork } = useChoices ( 'work' )
0 commit comments