TyForHelpDude
TyForHelpDude

Reputation: 5001

pass mobx observable data to props

Using mobx in react-typescript project. This class set observable array with fetch api:

class MenuRepo {
  @observable menuItems?: IMenuModel[];//=[{Id:1,itemName:"asd",childItems:[]}];
  @action getItems(): void {
    fetch(`...`)
      .then((response: { value: IMenuModel[] }): void => {
        this.menuItems = [
          { Id: 1, itemName: 'test-item1', childItems: [] }
        ];
      });
  }

and I want to track this observable data in this component class:

@observer
class Menu extends React.Component<{params?:IMenuModel[]}, {}> {
  render() {
    debugger
    var menuJSX : JSX.Element[] = this.props.params ? this.props.params.map((item:IMenuModel, i:number)=>{
      return (<li key={item.Id}>{item.itemName}</li>)
    }):[];
    return (...)

but params is "undefined". I watched some tutorials about mobx&react but couldnt solve it.

and here App.tsx file:

import menuCodes from './components/Codes';
class App extends React.Component<null, null> {
  render() {
    return (
      <div className="App">
        <Menu params = {asd.menuItems}/>
      </div>
    );
  }
}
export default App;

Upvotes: 2

Views: 2191

Answers (1)

mweststrate
mweststrate

Reputation: 4978

is asd instanceof MenuRepo? Note that in the first render menuItems will be undefined, as it only get's it's first value after the fetch has resolved, which should produce the second rendering.

Note that App should be observer as that is the one dereferencing the menuItems observable. (For more info: https://mobx.js.org/best/react.html)

Upvotes: 1

Related Questions