Fripo Fripo - 6 months ago 58
React JSX Question

Pass mobx store and props to function

I have a React component which calls a function, and i need to pass the injected mobx store and the components props into this function

const Component = inject("store")(observer(({store, props}) => {
return (
<div>
{_someRenderFunction(store, props)}
</div>
);
}));


It's used in the function like this

function _someRenderFunction(store, props) {
let data = store.data;
const { cookies } = props;
...
}


But i get the error
Cannot read property 'cookies' of undefined


How can i pass both the store and component props to the
_someRenderFunction
?

Answer Source

The problem is this line:

({store, props}) => {};

Your component receives only props so the basic definition would be:

(props) => {}

Inject gives you your injected store inside the given props. So what you receive is:

const props = { store: STORE_INSTANCE }

With the object destructing you can extract properties from props. So this would also work:

({ store }) => {}

Here you are extracting the property store from your props. but in your example you are also extracting the property props from props. So in your case props should look like:

const props = { store: STORE_INSTANCE, props: PROPS_OBJECT }

This is not what you want. So object destructing is not what you want in this case. The following code should work:

const Component = inject("store")(observer((props) => {
   return (
       <div>
          {_someRenderFunction(props)}
      </div>
   );
}));

function _someRenderFunction(props) {
   const { cookies, store } = props;
   let data = store.data;
   ...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download