Russo
Russo

Reputation: 3062

SolidJS SolidStart Context is not valid: How to setup initial Context state and update Context state after the page loads

Currently I am updating my state in each of my pages.

Where should I initialize my app state so the state can be displayed on every page in my app?

in my app.tsx or in entry-server.tsx ?

After that, I want to update the state after fetching data... I cannot use const { state, setState } = useCartContext(); in app.tsx because it is wrapping my Context there, and I got Context is not valid error.

export default function App() {
    const { state, setState } = useCartContext();// <-- crashed my app

    onMount(async () => {
        console.log("onMount from App()");
        const initOut = await initializeState();
        setState({ ...initOut });
    });

    return (
        <CartContextProvider>
            <Router
                root={(props) => (
                    <>
                        <SidebarDesktop sidebarItems={sidebarItems} />
                        <Nav />
                        <Suspense>{props.children}</Suspense>
                    </>
                )}
            >
                <FileRoutes />
            </Router>
        </CartContextProvider>
    );
}

Upvotes: 0

Views: 158

Answers (1)

Russo
Russo

Reputation: 3062

Okay so I think I should initialize my state inside my Context via onMount:

export const CartContextProvider: Component<CartContextProviderProps> = (
    props: CartContextProviderProps,
) => {
    const [state, setState] = createStore<StatesT>(default_state);
    onMount(async () => {
        ll("onMount from CartContextProvider()");
        const initOut = await initializeState();
        setState({ ...initOut });
    });
    return (
        <CartContext.Provider value={{ state, setState }}>
            {props.children}
        </CartContext.Provider>
    );
};

export const useCartContext = () => {
    const context = useContext(CartContext);
    if (!context) throw new Error("CartContext is not valid");
    return context;
};

Then my components can consume the updated state via Show:

const { state, setState } = useCartContext();
return (<div>
    <Show when={state.account.length > 0} fallback={"Connect Account"}>
        {state.account}
    </Show>
</div>);

Upvotes: 1

Related Questions