Context uses default value instead of one passed to provider

Hi! I've just started a new project using solid for the first time. as someone that comes from the react world, using context with createSignal seemed practically the same to me as in react, so I made a simple context to try it out.
export const LocaleContext = createContext<
[Accessor<'en' | 'he'>, () => 'he' | 'en' | void]
>([() => 'he' as const, () => {}]);

export const LocaleProvider: ParentComponent = ({ children }) => {
const [locale, switchLocale] = createSignal<'en' | 'he'>('en');
const switchLanguage = () => {
switchLocale((prev) => (prev === 'en' ? 'he' : 'en'));
return locale();
};
return (
<LocaleContext.Provider value={[locale, switchLanguage]}>
{children}
</LocaleContext.Provider>
);
};

export function useLocale() {
return useContext(LocaleContext);
}
export const LocaleContext = createContext<
[Accessor<'en' | 'he'>, () => 'he' | 'en' | void]
>([() => 'he' as const, () => {}]);

export const LocaleProvider: ParentComponent = ({ children }) => {
const [locale, switchLocale] = createSignal<'en' | 'he'>('en');
const switchLanguage = () => {
switchLocale((prev) => (prev === 'en' ? 'he' : 'en'));
return locale();
};
return (
<LocaleContext.Provider value={[locale, switchLanguage]}>
{children}
</LocaleContext.Provider>
);
};

export function useLocale() {
return useContext(LocaleContext);
}
and then I wrapped with it the router of my app.
<LocaleProvider>
<Router root={Layout}>
<LocaleProvider>
<Router root={Layout}>
and then I tried accessing it at two different places within the component tree.
export default function Navbar() {
const [locale, switchLocale] = useContext(LocaleContext);
export default function Navbar() {
const [locale, switchLocale] = useContext(LocaleContext);
but I just get the default values of the context (not the signal or the locale switcher, but the default value, and an empty function). Can anyone help me with some insight into why it happens? because I'm really confused...
1 Reply
lxsmnsyc
lxsmnsyc12mo ago
This is the issue ({ children }) => { you are destructuring basically you are rendering the children first before the parent.
Want results from more Discord servers?
Add your server