mobxjs / mobx

Simple, scalable state management.

Home Page:http://mobx.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using makeAutoObservable before variable initialization doesnt trigger state changes

Lucheti opened this issue · comments

Intended outcome:
Created a class, used makeAutoObservable. therefore, a observer component should re-render the ui when variable changes

Actual outcome:
ui didnt re-render

How to reproduce the issue:
this class is a singleton for stores:

export class AppStore {

  private static instance: AppStore

  authStore: AuthStore;

  postStore: PostStore;

  counter: Counter;

  private constructor() {
    makeAutoObservable(this)
    this.authStore = new AuthStore()
    this.postStore = new PostStore()
    this.counter = new Counter()
  }

  public static getInstance() {
    if (!AppStore.instance) {
      AppStore.instance = new AppStore();
    }
    return AppStore.instance;
  }
}

this is the postStore:

export class PostStore {
  posts: Post[];

  isLoading: boolean;

  constructor() {
    makeAutoObservable(this)
    this.posts = []
    this.isLoading = false
  }

  *fetchPosts() {
    this.isLoading = true
    const postsResponse = yield fetch('/api/posts')
    const posts = yield postsResponse.json()
    console.log("fetchPosts ", posts)
    this.posts = posts.map((post: PrismaPost) => new Post(post));
    console.log("fetchPosts ", this.posts)
    this.isLoading = false
  }

  *createPost({ title, content }: { title: string, content: string }): Generator<unknown, void, Post> {
    const post = yield fetch('/api/posts', {
      method: 'POST',
      body: JSON.stringify({ title, content })
    })
    this.posts.push(post)
  }
}

that doesnt work but moving the makeAutoObservable(this) to the end of the constructor in the postStore fixes the issue

Idk if its a bug or the intended way to work, but its not in the docs of the fn.

https://github.com/Lucheti/test-mobx-prisma-nextjs

Versions