Skip to content

Instantly share code, notes, and snippets.

@erick2014
Last active June 3, 2018 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erick2014/c1af39164c01ed831273147fabed912a to your computer and use it in GitHub Desktop.
Save erick2014/c1af39164c01ed831273147fabed912a to your computer and use it in GitHub Desktop.
React Context Api - Provider implementation
import { SESSION_SET_USER_INFO } from '../constants'
const sessionData = {
userName:'',
userId
}
const orders = {
orders: false
}
// context
export const AppContext = React.createContext()
export const AppConsumer = AppContext.Consumer
const reducer = (state, action) => {
switch (action.type) {
case SESSION_SET_USER_INFO:
const newSessionInfo = Object.assign({}, state.sessionData, action.payload)
return Object.assign({}, state, { sessionData: newSessionInfo })
}
}
export class AppProvider extends Component {
state = {
sessionData: sessionData,
orders: orders,
dispatch: action => {
this.setState(state => reducer(state, action))
}
}
_dispatch = action => {
this.setState(state => reducer(state, action))
}
render() {
const { state, props: { children } } = this
return (
<AppContext.Provider value={state}>
{this.props.children}
</AppContext.Provider>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment