Created
November 4, 2018 12:14
-
-
Save adeelibr/c12942dd4dcd7d2f5557449a0098b91d to your computer and use it in GitHub Desktop.
React Hooks useReducer
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 React, { useReducer } from 'react'; | |
const initialState = { | |
loading: false, | |
count: 0, | |
}; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'increment': { | |
return { ...state, count: state.count + 1, loading: false }; | |
} | |
case 'decrement': { | |
return { ...state, count: state.count - 1, loading: false }; | |
} | |
case 'loading': { | |
return { ...state, loading: true }; | |
} | |
default: { | |
return state; | |
} | |
} | |
}; | |
const delay = (time = 1500) => { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(true); | |
}, time); | |
}); | |
}; | |
function PokemonInfo() { | |
const [{ count, loading }, dispatch] = useReducer(reducer, initialState); | |
const onHandleIncrement = async () => { | |
dispatch({ type: 'loading' }); | |
await delay(500); | |
dispatch({ type: 'increment' }); | |
}; | |
const onHandleDecrement = async () => { | |
dispatch({ type: 'loading' }); | |
await delay(500); | |
dispatch({ type: 'decrement' }); | |
}; | |
return ( | |
<div> | |
<p>Count {loading ? 'loading..' : count}</p> | |
<button type="button" onClick={onHandleIncrement}> | |
+ | |
</button> | |
<button type="button" onClick={onHandleDecrement}> | |
- | |
</button> | |
</div> | |
); | |
} | |
export default PokemonInfo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment