Last active
May 17, 2019 18:57
-
-
Save dewey92/6f9b8fe958d0ea5b814c8a65e7ed31d5 to your computer and use it in GitHub Desktop.
Counter Reducer Solution
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
// useCounterReducer.js | |
import * as React from 'react'; | |
// Array destructuring disini sangat membantu code readability | |
const counterReducer = ([state, effect], action) => { | |
if (action.type === 'INCREMENT') { | |
return [state + 1]; | |
} | |
if (action.type === 'DECREMENT') { | |
if (state === 0) { | |
// Raise effect! | |
return [state, 'INVALID_STATE'] | |
} | |
return [state - 1]; | |
} | |
if (action.type === 'RESET_EFFECT') { | |
return [state]; | |
} | |
return [state, effect]; | |
} | |
// Hooks, kita ubah sedikit ya disini biar lebih clean | |
export const useCounterReducer = () => { | |
const [stateAndeffect, dispatch] = React.useReducer(counterReducer, [0]); | |
return [ | |
stateAndEffect, | |
{ | |
increment: () => dispatch({ type: 'INCREMENT' }), | |
decrement: () => dispatch({ type: 'DECREMENT' }), | |
resetEffect: () => dispatch({ type: 'RESET_EFFECT' }), | |
} | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment