Last active
June 3, 2018 22:16
-
-
Save erick2014/c1af39164c01ed831273147fabed912a to your computer and use it in GitHub Desktop.
React Context Api - Provider implementation
This file contains 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 { 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