1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-22 21:14:18 +00:00
pds-2021-g2-nest/code/frontend/src/hooks/useArrayState.js

42 lines
1.1 KiB
JavaScript
Raw Normal View History

import { useCallback, useState } from "react"
export default function useArrayState(def) {
const [value, setValue] = useState(def ?? [])
const appendValue = useCallback(
newSingle => {
2021-04-29 14:17:22 +00:00
console.debug("Appending ", newSingle, " to ArrayState")
setValue(
oldArray => [...oldArray, newSingle]
)
},
2021-04-29 03:03:34 +00:00
[]
)
2021-04-29 03:03:34 +00:00
const spliceValue = useCallback(
position => {
2021-04-29 14:17:22 +00:00
console.debug("Splicing ", position, " from ArrayState")
setValue(
oldArray => {
// TODO: Hope this doesn't break anything...
oldArray.splice(position, 1)
return oldArray
}
)
2021-04-29 03:03:34 +00:00
},
[]
)
const removeValue = useCallback(
remValue => {
2021-04-29 14:17:22 +00:00
console.debug("Removing ", remValue, " from ArrayState")
2021-04-29 03:03:34 +00:00
setValue(
2021-04-29 14:17:22 +00:00
oldArray => oldArray.filter(item => JSON.stringify(item) !== JSON.stringify(remValue))
2021-04-29 03:03:34 +00:00
)
},
[]
)
2021-04-29 03:03:34 +00:00
return {value, setValue, appendValue, spliceValue, removeValue}
}