Last active
November 26, 2018 16:02
-
-
Save isacjunior/812f93a1ba04ee8e21cb9ebdf1c7b794 to your computer and use it in GitHub Desktop.
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
// Counter Component | |
import React, { useReducer, createContext } from 'react' | |
import reducer, { initialState, actions } from './reducer' | |
const CounterContext = createContext() | |
function Counter() { | |
const [state, dispatch] = useReducer(reducer, initialState) | |
const { increment, decrement, reset } = actions(dispatch) | |
return ( | |
<CounterContext.Provider value={state}> | |
<> | |
Count: {state.count} | |
<button onClick={reset}> | |
Reset | |
</button> | |
<button onClick={increment}>+</button> | |
<button onClick={decrement}>-</button> | |
</> | |
</CounterContext.Provider> | |
) | |
} | |
export default Counter | |
// Reducer | |
import createReducer from 'core/utils/redux' | |
export const initialState = { | |
count: 0, | |
} | |
const types = { | |
increment: 'COUNTER/INCREMENT', | |
decrement: 'COUNTER/DECREMENT', | |
reset: 'COUNTER/RESET', | |
} | |
export const actions = (dispatch) => ({ | |
increment: () => dispatch({ type: types.increment }), | |
decrement: () => dispatch({ type: types.decrement }), | |
reset: () => dispatch({ type: types.reset }), | |
}) | |
const reducer = { | |
[types.increment]: (state) => ({ ...state, count: state.count + 1 }), | |
[types.decrement]: (state) => ({ ...state, count: state.count - 1 }), | |
[types.reset]: (state) => ({ ...state, count: 0 }), | |
} | |
export default createReducer(initialState, reducer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment