0

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.

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.