skip to Main Content

I am having an issue including my Legend state within my React Context in Typescript. Legend version (@legendapp/state) is 3.0.0-alpha.38, React version is 18.2.0, and Typescript version is 5.3.3. My setup is:

type Store = {
  stuff: string;
}


export type StevenContextType = {
  store: Observable<Store>;
};

const store$ = useObservable({
  stuff: "yo"
});

export const StevenContext = React.createContext<StevenContextType | null>(null);

<StevenContext.Provider value={{ store$ }}>

And the error message I’m getting is: Type {store$: ObservableObjectFunctions<ObservableProps<{stuff: string}> & NonObservableProps<{stuff: string}>> & ObservableChildren<ObservableProps<{stuff: string}>> & ObservableFunctionChildren<NonObservableProps<{stuff: string}>>} is not assignable to type StevenContextType | null

Any help would be deeply appreciated; I am sure there is a typing nuance that I’m just not grasping, but I cannot figure it out.

2

Answers


  1. in ts const store$ = useObservable({ stuff: "yo" });

    Instead of useObservable hook, use observable to create the store. This is the correct function from the Legend library to create an observable object

    Login or Signup to reply.
  2. It seems your issue is from the typing of the store$ objects returned by your useObservable hook. There is a high chance that what your StevenContext is expecting is not being returned by your useObservable hook. You can start by making sure the type you’re providing to StevenContext is properly described by what the useObservable hook is returning.

    type Store = {
      stuff: string;
    };
    
    export type StevenContextType = {
      store$: Observable<Store>;
    };
    
    const store$ = useObservable<Store>({
      stuff: "yo"
    });
    
    export const StevenContext = React.createContext<StevenContextType | null>(null);
    
    <StevenContext.Provider value={{ store$ }}>
    

    if after explicitly typing the observable using the correct return from the useObservable hook and updating the SteveContextType to match the observable object, and you still encounter this issue you might need to check your @legendapp/state for the correct types to use

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search