2021-04-29 02:28:33 +00:00
|
|
|
import { useCallback, useState } from "react"
|
|
|
|
|
|
|
|
|
2021-04-29 14:58:31 +00:00
|
|
|
/**
|
|
|
|
* An hook similar to {@link useState} which stores an array of values.
|
|
|
|
*
|
|
|
|
* @param def - The starting value of the hook.
|
|
|
|
* @returns {{spliceValue, removeValue, setValue, appendValue, value}}
|
|
|
|
*/
|
2021-04-29 02:28:33 +00:00
|
|
|
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")
|
2021-04-29 02:28:33 +00:00
|
|
|
setValue(
|
2021-05-11 14:37:15 +00:00
|
|
|
oldArray => [...oldArray, newSingle],
|
2021-04-29 02:28:33 +00:00
|
|
|
)
|
|
|
|
},
|
2021-05-11 14:37:15 +00:00
|
|
|
[],
|
2021-04-29 02:28:33 +00:00
|
|
|
)
|
|
|
|
|
2021-04-29 03:03:34 +00:00
|
|
|
const spliceValue = useCallback(
|
2021-04-29 02:28:33 +00:00
|
|
|
position => {
|
2021-04-29 14:17:22 +00:00
|
|
|
console.debug("Splicing ", position, " from ArrayState")
|
2021-04-29 02:28:33 +00:00
|
|
|
setValue(
|
|
|
|
oldArray => {
|
|
|
|
oldArray.splice(position, 1)
|
2021-05-11 21:44:14 +00:00
|
|
|
return [...oldArray]
|
2021-05-11 14:37:15 +00:00
|
|
|
},
|
2021-04-29 02:28:33 +00:00
|
|
|
)
|
2021-04-29 03:03:34 +00:00
|
|
|
},
|
2021-05-11 14:37:15 +00:00
|
|
|
[],
|
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-05-11 14:37:15 +00:00
|
|
|
oldArray => oldArray.filter(item => JSON.stringify(item) !== JSON.stringify(remValue)),
|
2021-04-29 03:03:34 +00:00
|
|
|
)
|
|
|
|
},
|
2021-05-11 14:37:15 +00:00
|
|
|
[],
|
2021-04-29 02:28:33 +00:00
|
|
|
)
|
|
|
|
|
2021-05-11 14:37:15 +00:00
|
|
|
return { value, setValue, appendValue, spliceValue, removeValue }
|
2021-04-29 02:28:33 +00:00
|
|
|
}
|