Add mobx to your React project

Mobx helps you manage the state.

I set up mobx to be used as an import to your (functional) components. I do this, rather than using createContext() because the latter one only allows you to use it inside components, not functions.

To set up mobx you’ll need to:

  1. install mobx
  2. create store
  3. configure store and components

In this example, I make use of the function autoStore() in the constructor of the store to save the state to localStorage whenever there is a change to the state.
This makes that state is saved across page-refreshes.

install mobx

Install with npm install --save mobx mobx-react.

create store

Create your store by creating file src/stores/applicationStore.js.

// file src/stores/applicationStore.js
import {action, computed, decorate, observable } from 'mobx'
import autoStore from '../libs/autoStore'

class ApplicationStore {
    greet = 'hello world'

    constructor() {
        // store changes to the state in localStorage
        autoStore(this)
    }

    setGreet(newGreet) {
        this.greet = newGreet
    }
}

decorate(ApplicationStore, {
    greet: observable,

    setGreet: action
})

const store = new ApplicationStore()
export default store

File ./src/libs/autoStore.js takes care of storing the state in localStorage.

// file ./src/libs/autoStore.js
import { toJS, autorun, set } from 'mobx'

export default function (_this) {
  let firstRun = true

  // will run on change
  autorun(() => {
    // on load check if there's an existing store on 
    // localStorage and extend the store
    if (firstRun) {
      const existingStore = window.localStorage.getItem('store')

      if (existingStore) {
        set(_this, JSON.parse(existingStore))
      }
    }

    // from then on serialize and save to localStorage
    const serializedThis = toJS(_this)
    window.localStorage.setItem(
       'store', 
       JSON.stringify(serializedThis)
    )
  })

  firstRun = false
}

configure store and components

Configure your components by wrapping them with the observer() function of mobx.

By doing this, mobx knows whenever something changes that concerns the state.

class component example:

// file ./src/components/greet.js

import React, { Component } from 'react'
import { observer } from 'mobx-react'
import store from "../stores/ApplicationStore";

class Greet extends Component {
  render() {
    return <div>{store.greet}</div>
  }
}

export default observer(Greet)

Functional component example:

// file ./src/components/SayHello.js

import React, { Component } from 'react'
import { observer } from 'mobx-react'
import store from "../stores/ApplicationStore";

const SayHello = () => {
   return <div>{store.greet}</div>
}

export default observer(SayHello)

Resources

Take a look at these pages. They provide useful information about working with mobx.

0 Shares
>