I have useState variable defined as such
const [queryBuilder, setQueryBuilder] = useState({location: [], metric: [], datetime: [], statistics: []})
then I have a function which should be able to set individual property back to empty array []. Here I ran into problem and I tried several ways but none worked, for example.
const clearCategory = (e, category) => {
setQueryBuilder(prev => { return {...prev, prev[category]: []}})
}
this wont work, but I try to access property via previous object and bracket notation (i also tried dot notation).
Normally I can access dynamically like so
queryBuilder[category]
but during useState hook I cant, how do I accomplish this ?
And, writing
setQueryBuilder(prev => {return {...prev, category: []}})
will just create a new property named category with an empty array
What you should use here is a computed property name, which is a feature introduced in ECMAScript 2015. For your example it will look like this:
{ ...prev, [category]: [] }
Note that the computed property itself doesn't reference your prev object and it's technically unrelated to it. It's simply a unique member of the object that overwrites any property with the same name from the prev object since it's being defined after prev was spread into the object.