Mike Hawkins
Mike Hawkins

Reputation: 2304

Using React hook to run Mobx method before initial render of component

As the title suggests, i have my state inside a Mobx store. I have an async method (action) that fetches the data and stores it in a property inside the store, from where i will access it in the necessary component.

Problem is, currently the property will be undefined on the initial component render - resulting in an error in the component.

How do i make use of useEffect() so that it runs an async method once and only once - and before the initial component render, ensuring the state will be available for return()? Something like this:

const Workflow = () => {
    const store = useContext(WorkflowContext)

    useEffect(async () => {
        await store.getWorkflow()
    }, [])
...

Upvotes: 1

Views: 1226

Answers (1)

Tholle
Tholle

Reputation: 112807

You can check if the property in the store is undefined and return null from the component if that is the case.

Example

const Workflow = () => {
  const store = useContext(WorkflowContext);

  useEffect(() => {
    store.getWorkflow();
  }, []);

  if (store.someProperty === undefined) {
    return null;
  }
  return <div>{store.someProperty}</div>;
};

Upvotes: 2

Related Questions