Skip to content

Commit

Permalink
ex0502: provide a state reducer action types.
Browse files Browse the repository at this point in the history
  • Loading branch information
eXvimmer committed Apr 11, 2023
1 parent db94fc6 commit 7d64a3a
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/exercise/05.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@ const callAll =
(...args) =>
fns.forEach(fn => fn?.(...args))

const actionTypes = {
toggle: 'toggle',
reset: 'reset',
}

function toggleReducer(state, {type, initialState}) {
switch (type) {
case 'toggle': {
case actionTypes.toggle: {
return {on: !state.on}
}
case 'reset': {
case actionTypes.reset: {
return initialState
}
default: {
Expand All @@ -27,8 +32,8 @@ function useToggle({initialOn = false, reducer = toggleReducer} = {}) {
const {current: initialState} = React.useRef({on: initialOn})
const [{on}, dispatch] = React.useReducer(reducer, initialState)

const toggle = () => dispatch({type: 'toggle'})
const reset = () => dispatch({type: 'reset', initialState})
const toggle = () => dispatch({type: actionTypes.toggle})
const reset = () => dispatch({type: actionTypes.reset, initialState})

function getTogglerProps({onClick, ...props} = {}) {
return {
Expand Down Expand Up @@ -60,7 +65,7 @@ function App() {

// this is the custom reducer
function toggleStateReducer(state, action) {
return action.type === 'toggle' && timesClicked >= 4
return action.type === actionTypes.toggle && timesClicked >= 4
? {on: state.on}
: toggleReducer(state, action)
}
Expand Down

0 comments on commit 7d64a3a

Please sign in to comment.