Tuesday, August 27, 2019

MobX without decorators and eject

Previous example was about using MobX with decorators. Although decorators makes the code more readable, it introduces transpilation complications. For ease of programming, it will be easier, if we can set aside MobX for React. From version 4.0 of MobX, we don't need decorations. Here's how to get to it

  1. npx create-react-app mobxwithoutdecoration
  2. cd mobxwithoutdecoration
  3. npm i mobx mobx-react
  4. mkdir -p src/components/stores/contactstore
  5. touch src/components/stores/contactstore/index.js

Open contactstore/index.js and add the following contents

import { observable, action, computed, decorate } from "mobx";
class ContactStore {
  contacts = [];
  addContact = contact => {
    console.log("A new contact is added");
    console.log(contact);
    this.contacts.push(contact);
  };
  get contactsCount() {
    return this.contacts.length;
  }
}
decorate(ContactStore, {
  contacts: observable,
  addContact: action,
  contactsCount: computed
});
export default new ContactStore();


As you can see from the above code, we no longer have @observable or @action etc.

Your component to consume provider can be achieved in the following way
import React from 'react';
import { inject, observer } from "mobx-react";
class App extends React.Component {
  render() {
    return (
      ....
      ....
    )
  }
}
export default inject("contactStore")(observer(App));

As you can see we no longer have @observer or @inject. They have rather been converted to HOC components internally.

index.js continues to be the same as it was before. For full code check out here

No comments: