SolidJSS
SolidJSโ€ข3y ago
Robin Lindner

useContext returns undefined.

Hey I created a Provider and a context to manage figlet fonts.

This provider is just a "singleton"-reference to my FontRegistry.

FontProvider + useFonts:
import { createSignal, createContext, useContext, FlowComponent, FlowProps } from "solid-js";
import { FontRegistry } from "../../core/fonts/font-registry";

const FontContext = createContext<FontRegistry>();

export const useFonts = () => useContext(FontContext);
export const FontProvider = (props: FlowProps) => {
    const fontRegistry = new FontRegistry();
    const [fonts, _setFonts] = createSignal<FontRegistry>(fontRegistry);

    return <FontContext.Provider value={fonts()}>
        {props.children}
    </FontContext.Provider>;
}


Child-Component:
export const TextToAscii = () => {
    const fonts = useFonts(); // -> undefined
    const fontIterable = Array.from(fonts?.fonts ?? []);

    return <div>
        <For each={fontIterable}>
            {(font) => <div>{font.name}</div>}
        </For>
    </div>
};


For some reason useContext returns undefined.
I use Astro for this, but even in client:only mode it does not work.

Astro page:
---
import { FontProvider } from "../components/FontProvider/FontProvider";
import { TextToAscii as TextToA } from "../components/TextToAscii/TextToAscii";
---

<html lang="en">
    <head>
        <!-- ... -->
    </head>
    <body>
        <FontProvider client:only>
            <TextToA client:only />
        </FontProvider>
    </body>
</html>
Was this page helpful?