im4ever
im4ever

Reputation: 517

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 };
});

Upvotes: 4

Views: 6643

Answers (1)

Related Questions