/** * Custom Implementation of React Context to manage * global application state * * @author Sheharyar Naseer (@sheharyarn) * @license MIT * * Normal Usage: * * ``` * * { (context, setContext) => (/* do something */) } * * ``` * * HOC Usage: * * ``` * export default AppContext.withConsumer(MyComponent); * ``` * * Links: * - https://reactjs.org/docs/context.html * - https://auth0.com/blog/react-context-api-managing-state-with-ease/ * - https://medium.freecodecamp.org/reacts-new-context-api-how-to-toggle-between-local-and-global-state-c6ace81443d0 */ import React from 'react' // TODO: // Have a separate SessionContext ? const Context = React.createContext({}); const initialContext = { env: process.env.NODE_ENV, session: { signedIn: false, user: null, token: null, } }; // Custom Provider class Provider extends React.Component { constructor(props) { super(props); this.state = { context: initialContext, setContext: this.handleSetContext.bind(this), }; } handleSetContext(context) { const newContext = Object.assign(this.state.context, context); this.setState(newContext); } render() { const {env} = this.state.context; if (env === 'development') console.log("Global Context:", this.state.context); return ( {this.props.children} ); } } // Custom Consumer class Consumer extends React.Component { render() { const {children} = this.props; return ( { ({context, setContext}) => children(context, setContext) } ); } } // ContextualComponent HOC const withConsumer = (Component) => { return function ContextualComponent(props) { return ( { (consumer) => } ); }; } // Export Methods export default {Provider, Consumer, withConsumer};