2

In my SolidJS and SolidStart project, I declared my CartContext in my CartContext.tsx


export const CartContext = createContext<>();

const stateDefault = { ... };
export type StatesT = typeof stateDefault;

export const CartContextProvider: Component<CartContextProviderProps> = (
    props: CartContextProviderProps,
) => {
    const [state, setState] = createStore<StateT>(stateDefault);

    return (
        <CartContext.Provider value={{ state, setState }}>
            {props.children}
        </CartContext.Provider>
    );
};

export const useCartContext = () => useContext(CartContext);

But when I use this context in my components:

const { state, setState } = useCartContext();

TypeScript gave me warning: Property 'state' does not exist on type 'unknown'.ts(2339)

1 Answer 1

1

Okay I figured it out. I needed to add a type at createContext()

according to the CartContext.Provider value={{ state, setState }}:

export type cartContextType = {
    state: StatesT;
    setState: (state: StatesT) => void;
};
export const CartContext = createContext<cartContextType>();

Then TypeScript gave me another warning: Property 'state' does not exist on type 'cartContextType | undefined'.ts(2339)

according to this docs: https://docs.solidjs.com/reference/component-apis/create-context, you need to handle context === undefined case:

export const useCartContext = () => {
    const context = useContext(CartContext);
    if (!context) throw new Error("CartContext is not valid");
    return context;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.