React JS: How to get MobX store's state using observer in a custom hook?

Viewed 1579

Use case:

I have a custom hook useFoo which needs to return values based on bar property in store but typescript throws error.

Code:

export const useFoo = observer(() => {
// typescript throws error --^^^^^^^--

  const { bar } = store;

  return bar ? 'x' : 'y';
});

Typescript Errors:

Argument of type '() => "x" | "y"' is not assignable to parameter of type 'IReactComponent<any>'.
  Type '() => "x" | "y"' is not assignable to type 'FunctionComponent<any>'.
    Type '"x" | "y"' is not assignable to type 'ReactElement<any, any> | null'.
      Type '"x"' is not assignable to type 'ReactElement<any, any> | null'.ts(2345)
1 Answers

Probably your concept is not full correct from architecture point of view, cause custom hook should be isolated from data to be reusable

https://github.com/mobxjs/mobx-react-lite/issues/67

useDisposable(
  () => mobx.reaction(() => loadingStatusStore.lastRefreshDate,
  refreshDate => {
    // here you can do rest of the `useEffect`, but you need to use that `refreshDate` here,
    // otherwise, MobX won't even bother running it since you are not really using an observed variable.
  }
)
Related