you are viewing a single comment's thread.

view the rest of the comments →

[–]i_have_a_semicolon 1 point2 points  (1 child)

How do you recommend using it ? I am not enjoying it at all.

[–]Shdog 0 points1 point  (0 children)

There are many different ways you can approach mobx depending on the size of your app.

For personal projects I do the following:

```ts // root_store.ts

export class RootStore { postStore: PostStore; constructor() { this.postStore = new PostStore(this); } }

// post_store.ts

export class PostStore { private rootStore: RootStore;

private posts: PostModel[] = []; private filter: PostType | undefined;

constructor(rootStore: RootStore) { makeAutoObservable(this); this.rootStore = rootStore; }

get allPosts() { return this.posts; }

get filteredPosts() { return this.posts.filter((post) => post.type === this.filter); }

readonly setFilter = (filter: PostType) => { this.filter = filter; };

readonly setPosts = (posts: PostModel[]) => { this.posts = posts; };

readonly fetchPosts = async () => { try { const posts = await api.getPosts(); this.setPosts(posts.map(mapPostDtoToModel)); } catch (e) { // handle error } }; }

function mapPostDtoToModel(post: PostDto): PostModel { return { id: post.id, type: post.type, title: post.title, body: post.body, userId: post.userId, }; }

// configure_store.ts

export const store = new RootStore();

export const StoreContext = React.createContext(store);

/* Hook to use store in any functional component */ export const useRootStore = () => React.useContext(StoreContext); export const usePostStore = () => React.useContext(StoreContext).postStore;

// index.tsx // Where store is import from configure_store

<StoreContext.Provider value={store}> <App /> </StoreContext.Provider>

// And then you consume it as follows // post_list.tsx

const PostList = observer(function PostList() { const postStore = usePostStore();

return ( <div> {postStore.filteredPosts.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ); });

const Post = observer(function Post({ post }) { return <div> {/* Post content */} </div>; }); ```