Jithin Varghese
Jithin Varghese

Reputation: 2228

removing value from array not working NEXT.JS

I have a filter options, which shows checkbox. So when click on each checkbox the value should be added to array if not exists and remove the value from array if already exists and the state should be updated. I have tried using below code and it is not working.

const [showFilter, setFilter] = useState([]);

useEffect(() => {
    dispatch(fetchproducts(slug, sort, pageInitial+1, showFilter));
    console.log(showFilter);
}, [showFilter]);

function filterClick (id, title) {
    const index = showFilter.indexOf(id);

    if (index > -1)
        setFilter(showFilter.splice(index, 1));
    else
        setFilter(showFilter.concat(id));
}

return (
    <ul style={{display: showMe.includes(index) ? "block" : "none"}}>
        {item.items.map((single, index1) => (
            <li key={index1}>
                <label><input type="checkbox" name="checkbox" onClick={(e) => filterClick(e.target.value, item.title)} value={single.items_id}/> {single.items_value}</label>
            </li>
        ))}
    </ul>
)

In the above code, array insertion is working, but the splice is not working and the state is not updating.

How to alter my code to get the expected result.

Upvotes: 0

Views: 2523

Answers (2)

Ramil Garipov
Ramil Garipov

Reputation: 473

You use useEffect. The useEffect's callback will be triggered when one of dependency is changed.

splice function changes array in place (ie mutates the array). In this case your array variable (showFilter) is not changed, therefore useEffect's callback will not be triggered.

Try using filter function instead:

setFilter(showFilter.filter(el=> el !== id));

Upvotes: 1

ranjan_purbey
ranjan_purbey

Reputation: 451

Splice modifies the original array which is not considered a good practice in React. Please use slice or`filter.

Using slice your code would look like:

setFilter(showFilter.slice(index, index + 1))

Upvotes: 1

Related Questions