Skip to content

Instantly share code, notes, and snippets.

@lequanghuylc
Last active May 31, 2019 09:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lequanghuylc/2d9c0ff12c6ac64557c0acb4a0987ff1 to your computer and use it in GitHub Desktop.
[Global Store in React using context] #react
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Root extends Component {
static childContextTypes = {
appState: PropTypes.func
};
getChildContext = () => {
return {
appState: this.appState
}
}
state = {
message: "Hello World"
}
appState = (objOrFunc, func) => {
if (typeof objOrFunc === 'string') return this.state[obj];
const isParamValid = typeof objOrFunc === 'object' || typeof obj === 'function';
if (isParamValid === true && typeof func === 'undefined') {
this.setState(objOrFunc);
} else if (isParamValid === true && typeof func === 'function') {
this.setState(objOrFunc, () => {
func();
})
} else {
return false;
}
}
}
class Child extends Component {
componentWillMount() {
this.store = this.context.appState;
typeof this.willMount === "function" && this.willMount();
}
static contextTypes = {
appState: PropTypes.func
}
}
/*
When creating Components, make sure extends Root & Child instead of Component (only extends Root once)
Then we can use this.store at Child. For this example:
this.store("message") will return "Hello World"
this.store({ message: "Hi" }) will setState Root and re-render
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment