Skip to content

Instantly share code, notes, and snippets.

@KDCinfo
Last active May 1, 2018 21:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KDCinfo/524a4113fda532f4376317f64bb47696 to your computer and use it in GitHub Desktop.
Save KDCinfo/524a4113fda532f4376317f64bb47696 to your computer and use it in GitHub Desktop.
MobX Uber-Simplified Boilerplate

MobX Uber-Simplified (mostly stripped) Boilerplate

Based on: YouTube: Easy MobX and Redux Comparison (Mar 2018)

MobX: Basic Flow

Action: Functions 
	--> (updates)
		--> Observable Properties: State
			|--> (updates / to render current dom)
			|--> Computed Perform Operations
	^
	|		\	--> View / Component
	\---------------/ (actions are triggered / called in the view)

[GalleryStore.js]

import { observable, action, runInAction } from 'mobx';
export default class GalleryStore {
	@observable term = "";
	@observable images = [];
	@observable status = 'initial';
	@action
	fetchImages = async term => {
	this.term = term;
		this.images = [];
		this.status = 'searching';
		try {
			const response = await axios.get('http...', {params: {}});
			this.setImages(response.data.results);
		} catch (error) {
			runInAction(() => { this.status = 'error'; });
}	};	} // <-- Please never do this for real. :)

[index.js]

import { Provider } from 'mobx-react';
import GalleryStore from "./stores/GalleryStore";
const galleryStore = new GalleryStore(); // from `class GalleryStore {}`
ReactDOM.render( <Provider galleryStore={galleryStore}><App /></Provider>, root );

[App.js]

import { inject, observer } from 'mobx-react';
@inject("galleryStore")
@observer
export default class App extends React.Component {
	componentDidMount() { this.props.galleryStore.fetchImages("Mountains"); }
	render() { // const { term, status, images } = this.props.galleryStore; return (); }
}

[Form.js]

import { inject, observer } from 'mobx-react';
@inject("galleryStore")
@observer
export default class Form extends React.Component {
	// this.props.galleryStore.fetchImages(term);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment