Last active
April 18, 2019 15:23
-
-
Save EduVencovsky/f0e1f77f93b6a67492827a64db775349 to your computer and use it in GitHub Desktop.
React Hook for using arrays
This file contains hidden or 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 { useReducer } from 'react' | |
| function arrayReducer(array, action) { | |
| switch (action.type) { | |
| case 'push': | |
| return [...array, action.value] | |
| case 'pushAll': | |
| return [...array, ...action.value] | |
| case 'deleteByIndex': | |
| let deleteByIndex = array.filter((x, i) => i != action.index) | |
| return deleteByIndex | |
| case 'updateByIndex': | |
| let updateByIndex = [...array] | |
| updateByIndex[action.index] = action.value | |
| return updateByIndex | |
| case 'mergeByIndex': | |
| let mergeByIndex = [...array] | |
| Object.assign(mergeByIndex[action.index], action.value) | |
| return mergeByIndex | |
| default: | |
| throw new Error() | |
| } | |
| } | |
| export default function useArray(initialState) { | |
| return useReducer(arrayReducer, initialState) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment