Last active
May 31, 2019 09:59
-
-
Save lequanghuylc/2d9c0ff12c6ac64557c0acb4a0987ff1 to your computer and use it in GitHub Desktop.
[Global Store in React using context] #react
This file contains hidden or 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 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