I want to initialize a React state as an empty Set in Typescript, and then add/remove values.
If I wanted to use an array, I would do this:
const [products, setProducts] = React.useState<String[]>([])
// And then to change it:
setProducts([...products, "new product"])
But I want to use a Set, so every value has to be unique. How can I do this?
>Solution :
A Set is a mutable data structure, while the state should be immutable. When you need to update the state, first create a new Set off the old Set:
const next = new Set(prev) // prev is the old Set
Now you can update the new Set (next), and set it as the new state.
Initializing the state once using an initializer function:
const [products, setProducts] = React.useState<String[]>(() => new Set())
Adding a value to the state:
setProducts(prev => {
const next = new Set(prev) // create a new Set from the old one
next.add(val) // add a value to the new Set
return next
})
Removing a value from the state:
setProducts(prev => {
const next = new Set(prev) // create a new Set from the old one
next.delete(val) // remove a value from the new Set
return next
})