Created
June 13, 2018 03:21
-
-
Save ldiego08/98baed3e80c808b85db388a27bc8d35a to your computer and use it in GitHub Desktop.
State Management - MobX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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