Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject mobx store into a stateless component

Tags:

I am using mobx and react in a web application and I want to find a way to pass mobx store state to a stateless component. Below is my current component source code:

import React from 'react'; import Panel from './Panel'; import {inject, observer} from 'mobx-react';  @inject(allStores => ({   form: allStores.store.form, })) @observer export default class Creator extends React.Component {    connect() {     console.log(this.props.form);   };    render() {     return (       <Panel form={this.props.form} connect={this.connect.bind(this)}/>     );   } }; 

How can I change it to be stateless? I tried below code but didn't work:

const Creator = ({form}) => {    const connect = ()=>{     console.log('xxxx,', form);   }    return (     <Panel form={form} connect={connect}/>   ); }  export default observer(Creator); 

when I run above code, I got undefined value for form on the connect method. How can I inject the store into stateless component? I tried to use @inject on top of stateless component, but got a syntax error.

like image 201
Joey Yi Zhao Avatar asked Mar 22 '17 05:03

Joey Yi Zhao


People also ask

How do you inject a MOBX store in the functional component?

import React from 'react'; import Panel from './Panel'; import {inject, observer} from 'mobx-react'; @inject(allStores => ({ form: allStores. store. form, })) @observer export default class Creator extends React. Component { connect() { console.

Can MOBX be used in functional components?

Note that mobx-react fully repackages and re-exports mobx-react-lite , including functional component support. If you use mobx-react , there is no need to add mobx-react-lite as a dependency or import from it anywhere. Note: observer or React.

What is inject in MOBX?

The store injection pattern was popularized by the mobx-react library. It refers to a now obsolete way of accessing the MobX stores across the component tree. It was introduced because the React legacy context was rather awkward to use. We are in 2019 now and we don't need injections anymore (kids, don't do drugs).

Can I use MOBX in react native?

With the introduction of the new Context API, there is no need to use Provider pattern with MobX and you can now just use the React Context API.


1 Answers

inject returns a function that you can use on a observer functional component:

var Example = inject("myStore")(observer((props) => {   // ... })); 
like image 189
Tholle Avatar answered Oct 16 '22 00:10

Tholle