Skip to content

Instantly share code, notes, and snippets.

@ldiego08
Created June 13, 2018 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldiego08/98baed3e80c808b85db388a27bc8d35a to your computer and use it in GitHub Desktop.
Save ldiego08/98baed3e80c808b85db388a27bc8d35a to your computer and use it in GitHub Desktop.
State Management - MobX
import { observable, action, extendObservable } from 'mobx';
export class TagsStore {
private static defaultState: any = {
query: '',
isLoading: false,
results: [],
};
@observable public results: string[];
@observable public isLoading: boolean;
@observable public query: string;
constructor(initialState: any) {
extendObservable(this, {...defaultState, ...initialState});
}
@action public loadTags = (query: string) => {
this.query = query;
// do something here ..
}
}
export interface StoreMap {
tags: TagsStore,
}
import React, { Component } from 'react';
import { inject, Provider } from 'mobx-react';
import { Header, HeaderProps } from './header';
export interface HomePageProps {
headerProps?: HeaderProps;
}
export class HomePage extends Component<IndexPageProps> {
render() {
return (
<Header {...this.props.headerProps} />
<!-- the rest of the page .. -->
);
}
}
export interface StoreMap {
tags: TagsStore;
}
export const ConnectedHomePage = inject(({ tags }: StoreMap) => ({
headerProps: {
searchBoxProps: {
query: tags.query,
isLoading: tags.isLoading,
data: tags.data,
onSearch: tags.loadTags,
}
}
}));
export const tagsStore = new TagsStore();
export default () => {
return (
<Provider tags={tagsStore}>
<ConnectedHomePage>
</Provider>
);
}
import { action, flow } from 'mobx';
export class TagsStore {
// ..
@action public loadTags = flow(function * (query: string) {
this.query = query;
this.isLoading = true;
try {
const tags = yield fetch('http://somewhere.com/api/tags');
this.tags = tags;
} catch (err) {
this.err = err;
}
this.isLoading = false;
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment