H
H
Harconnen2020-07-07 09:36:46
React
Harconnen, 2020-07-07 09:36:46

How to get state from Mobx React.js store?

Hello, I'm studying Mobx and stumbled, I can't understand what is the reason.

import { observable, action } from 'mobx';

class SetingStore {
    @observable app

    constructor() {
      this.setSeting()
    }
    // @computed get isSetSeting() {
    //   return this.app
    // }
    @action setSeting() {
      fetch('./static/setings.json')
      .then(response => response.json())
      .then(data => {this.app = data.app})
    }

}
const setingStore = new SetingStore()

export default setingStore
export { SetingStore }


Here's what I'm trying to get out.

import React, { Component } from "react"
import { Provider } from 'mobx-react'
import {configure } from 'mobx'

/* stores */
import setingStore from './stores/seting-store'
import menuStore from './stores/menu-store'

/* components */
import Menuapps from './components/Menuapps'
import Titlehead from "./components/Titlehead"
import Sprite from "./components/Sprite"

// Строгий режим
configure({ enforceActions: 'observed' })

const stores = { setingStore, menuStore }

class App extends Component {
  render() {
    return (
      <Provider { ...stores }>
        <div className="body">
          <header>
            {console.log(setingStore.app)}
            <Menuapps />
            <Titlehead />
            {/* {setingStore.app === "default" ? 'nav' : ''} */}
          </header>
          
          <Sprite/>
        </div>
      </Provider>
    )
  }
}
export default App


I can not understand why "setingStore.app" writes undefined
Please help me understand

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Didenko, 2020-07-07
@Harconnen

Because you are pulling the store from the closure, not from the provider.
Create a component, render it inside a Provider, wrap it in inject('settingStore') and it will work. Well, correct the typo with seting -> setting
For brevity, you can export it like this export default new SettingsStore()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question