Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX React: Define a observer hook

I'm trying to define my own hooks in a MobX project which depend on mobx observables. But it's not possible to wrap a hook with observer() because observer() must return a component. Is there a way to define observer hooks?

Example:

// not working because observer must return a component
const useFindSuggestion = observer(({ target, node, suggestionsStore }: LinkSuggestionWrapperProps) => {
  const [suggestions, setSuggestions] = useState<IDocumentInfo[]>([]);

  useEffect(() => {
    const suggestions = suggestionsStore.getRelevantSuggestions(node, target).filter((s) => s.documentId !== node.target);
    setSuggestions(suggestions);
  }, []);

  return { suggestions };
});
like image 547
im4ever Avatar asked Sep 13 '25 08:09

im4ever


1 Answers

Solution: use autorun within hook https://mobx.js.org/react-integration.html#useeffect

Example: https://codesandbox.io/s/minimal-mobx-react-project-forked-8gnxgt?file=/index.js

like image 98
im4ever Avatar answered Sep 15 '25 14:09

im4ever