Jonathan Sandler
Jonathan Sandler

Reputation: 335

useState creating multiple arrays

I am creating a dropdown filter to update the search results of a page using react hooks. Basically, I am passing an array with the options that the user chose from the dropdown menu. I am successfully updating the global state with the new arrays BUT my issue is useState creates a NEW array instead of merging the results with the previous state. enter image description here

Above you can see, I made two calls with different filter options and the global state now holds 2 arrays. My goal is to have both arrays merged into one.

This is the function where the global state is being updated.

const Results = () => {
    const [filterList, setFilterList] = useState([])

    const setGlobalFilter = (newFilter) => {
        let indexFilter = filterList.indexOf(newFilter);

        // console.log("Top level index", indexFilter)

        indexFilter ?
        setFilterList([...new Set([...filterList, newFilter])]) :
        setFilterList(filterList => filterList.filter((filter, i) => i !== indexFilter))
    }

    // console.log("TopFilterSelection:", filterList)
    return (
        <div>
            <Filter setFilter={(filterList) => setGlobalFilter(filterList)}/>
        </div>
    )
}

I've been checking on using prevState like this:

...
        setFilterList(prevState => [...new Set([...prevState, newFilter])]) :
...

But I don't know what I am doing wrong. Any feedback would be much appreciated!

Upvotes: 0

Views: 1276

Answers (2)

Aleks
Aleks

Reputation: 984

This happens because newFilteris an array, not a word. Should be

setFilterList(previous => [...new Set([...previous, ...newFilter])])

Also this

let indexFilter = filterList.indexOf(newFilter);

always returns -1 if newFilteris an array (since you a sending brand new array each time), it's not a falsy value, be careful

Upvotes: 1

Justin Punzalan
Justin Punzalan

Reputation: 21

Use the .concat method.

setFilterList(filterList.concat(newFilter))

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Upvotes: 0

Related Questions