mobx
mobx copied to clipboard
Using makeAutoObservable before variable initialization doesnt trigger state changes
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
Please make sure your compiler is set up properly https://mobx.js.org/installation.html#use-spec-compliant-transpilation-for-class-properties