I'm just getting started with SolidJs and am learning about Context. It seems like this might be a good way to inject singleton services throughout my application, some of which might be reactive. Is that an appropriate use? For example, I might have an authentication service for handling determining who is the current user and provide a sign out method. I might configure database access too, such as whether to work with a local emulator or the real db. Here is a stripped down version of how it works, with string
substituting for the actual services and all the configuration of them. It makes sense to me to configure these services as props on the ServicesProvider on the root. Also notice I've made the ServicesContext variable private to the module and nullable, because I don't want to define a default value; instead I want the value defined as a function of parameters passed to the Provider object. This is different than the samples I've seen since the variable is not exported.
let ServicesContext: Context<string> | undefined = undefined;
export function ServicesProvider(props: {
useMocks: boolean;
children: JSXElement;
}) {
const svcs = props.useMocks ? "mocks" : "real stuff";
ServicesContext = createContext(svcs);
return (
<ServicesContext.Provider value={svcs}>
{props.children}
</ServicesContext.Provider>
);
}
export function useServices() {
if (ServicesContext === undefined)
throw new Error(
"Trying to use the services context when it hasn't been rendered."
);
return useContext(ServicesContext);
}
// When using the provider, I want to configure all the services
// here, like whether they are mocked or not and other settings.
render(
() => (
<ServicesProvider useMocks={true}>
<RootApp />
</ServicesProvider>
),
root
);