Tushar Chutani
Tushar Chutani

Reputation: 1570

React component not updating when the MobX object updates

I just started using MobX so pardon me if I am missing something very trivial here. To get my feet wet I just built a simple add subtract project that makes use of contexts. There are 3 components I made AddButton, SubtractButton and Answer. All reading and updating an instance of a class that makes use of observable.

CodeSandbox: https://codesandbox.io/s/stoic-chandrasekhar-kz5e9?file=/src/App.tsx

The intention is to update the Answer component whenever the AnswerStore changes. (The answer is wrapped in observer HOC)

This is what the store looks like

export class AnswerStore {
  @observable
  answer = 0;

  @action
  add() {
    console.log("Adding 1 to ", this.answer);
    this.answer = this.answer + 1;
  }

  @action
  sub() {
    console.log("Subtracting 1 from ", this.answer);
    this.answer = this.answer - 1;
  }
}

const context = React.createContext({} as AnswerStore);
export const useStore = () => React.useContext(context);

The Answer component looks like this

import { observer } from "mobx-react-lite";
import React from "react";
import { useStore } from "./store";

const answer = observer(() => {
  const store = useStore()
  return <h1>Answer is: {store.answer}</h1>;
})


export default answer

Again I am not sure what I am missing here :/

Upvotes: 0

Views: 493

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

const context = React.createContext({} as AnswerStore);

The "as" statement is Typescript, it says what type {} should be treated as.

It only exists in Typescript, as Typescript types don't exist in the generated Javascript after compilation. So context is initialized with a normal empty object, and not an observable.

If instead you do

const context = React.createContext(new AnswerStore());

Then as far as I can see, it should work.

Upvotes: 1

Related Questions