reactjsstatemobxmobx-react-liteglobal-state

How to trigger a state like setState with MobX, mobx-react-lite?


I want to carry to states into the global state with mobx. I'm struggling to create a global state in mobx. Also, I would like to mention that I'm using mobx-react-lite library.

Here is the link to codesanbox. If you open the commands, you will be able to see how it works before with useState. https://codesandbox.io/s/mobx-react-lite-example-dfkm2y?file=/src/App.tsx

This is my store

import { observable, action } from "mobx";

export class ProductStore {
  @observable categories: string[] = [];

  @action
  addCategory = (val: string) => {
    this.categories.push(val);
  };

  @action
  removeCategory = (val: string) => {
    this.categories = this.categories.filter((f) => f !== val);
  };
}

Here is my context

import { createContext, useContext } from "react";
import { ProductStore } from "./productStore";

type ProductContextValue = {
  productStore: ProductStore;
};

const ProductContext = createContext<ProductContextValue>(
  {} as ProductContextValue
);

const productStore = new ProductStore();

export const ProductProvider: React.FC<React.PropsWithChildren<{}>> = ({
  children
}) => {
  return (
    <ProductContext.Provider value={{ productStore }}>
      {children}
    </ProductContext.Provider>
  );
};

export const useStore = () => useContext(ProductContext);

I use addCategory and removeCategory action in my component. When I'm doing debugging, I can see that actions work correctly.

However, I can not reach the categories of updates.

Here is the parent component

import "./styles.css";
import { ExampleComponent } from "./ExampleComponent";
import { useStore } from "./ProductContext";
import { useObserver } from "mobx-react-lite";
// import { useState } from "react";

export default function App() {
  // const [selectedCategories, setSelectedCategories] = useState<string[]>([]);

  const { productStore } = useStore();

  return useObserver(() => (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      {/* old Version with useState */}
      {/* {selectedCategories.map((m) => {
        return <div>{m}</div>;
      })} */}

      {/* This section not working like a setState */}
      {productStore.categories.map((m) => {
        return <div>{m}</div>;
      })}

      <ExampleComponent
        // selectedCategories={selectedCategories}
        // setSelectedCategories={setSelectedCategories}
        addCategory={productStore.addCategory}
        removeCategory={productStore.removeCategory}
      />
    </div>
  ));
}

How Can I fix this problem? I can not see any changes in the mobx section.


Solution

  • First of all you need to use makeObservable inside store constructor to make it work with decorators now, like that:

    import { observable, action, makeObservable } from 'mobx';
    
    export class ProductStore {
      @observable categories: string[] = [];
    
      constructor() {
        makeObservable(this);
      }
    
      @action
      addCategory = (val: string) => {
        this.categories.push(val);
      };
    
      @action
      removeCategory = (val: string) => {
        this.categories = this.categories.filter((f) => f !== val);
      };
    }
    

    And second, don't use useObserver it's deprecated, use <Observer> component or wrap entire component with observer HOC.

    Working Codesandbox