React mobx can't get observable's value

Viewed 221

Below is my store which will retrieve observable units from an API by using the loadUnits method, the API is working well, I also added a console.log() here, I can see the first element's value.

import { ITutorialUnit } from "./../model/unit";
import { action, observable } from "mobx";
import { createContext } from "react";
import agent from "../api/agent";

class UnitStore {
  @observable units: ITutorialUnit[] = [];
  @observable title = "hello from mobx";
  @observable loadingInitial = false;

  @action loadUnits =  () => {
    this.loadingInitial = true;
    agent.TutorialUnits.list()
      .then(units => {
        units.forEach((unit) => {
          this.units.push(unit);
        });
      })
      .then(() => console.log("from store:" + this.units[0].content))  // I can see the data from this logging
      .finally(() => (this.loadingInitial = false));
  };
}
export default createContext(new UnitStore());

then when I want to use the observable units in App.tsx :

import React, { Fragment, useContext, useEffect, useState } from "react";
import { Container } from "semantic-ui-react";
import "semantic-ui-css/semantic.min.css";
import NavBar from "../../features/nav/NavBar";
import { ActivityDashboard } from "../../features/Units/dashboard/tutorialUnitDashboard";
import UnitStore from "../stores/unitStore";
import { observer } from "mobx-react-lite";
import { LoadingComponent } from "./LoadingComponent";
import agent from "../api/agent";
import { ITutorialUnit } from "../model/unit";

const App = () => {
  const unitStore = useContext(UnitStore);
  const units = unitStore;
  useEffect(() => {
    unitStore.loadUnits();
    console.log("from App.tsx: " + units);           // will only log a undefined
  }, [unitStore]);
  if (unitStore.loadingInitial) {
    return <LoadingComponent content="Loading activities..." />;
  }

  return (
    <Fragment>
      <NavBar />

      <Container style={{ marginTop: "7em" }}>
        <h1>{unitStore.title}</h1>
        <ActivityDashboard />
      </Container>
    </Fragment>
  );
};

export default observer(App);

I can't get the observable units's data, but I can get another observable title's data, which is just a string, the LoadingComponent is not working either. please help me!

1 Answers

I figured this out. the version of Mobx should below 6.0.0, i use 5.10.1 and everything's just fine.

Related