Skip to content

Instantly share code, notes, and snippets.

@EduVencovsky
Last active April 18, 2019 15:23
Show Gist options
  • Save EduVencovsky/f0e1f77f93b6a67492827a64db775349 to your computer and use it in GitHub Desktop.
Save EduVencovsky/f0e1f77f93b6a67492827a64db775349 to your computer and use it in GitHub Desktop.
React Hook for using arrays
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