0

I am making a filter that allows user clicks a checkbox to do filter. When I click a checkbox, It will add that object of item into an array of filters. When clicking again that item, I will remove that item from the array.

I am using a hard code for the object of item to make sure they are the same object every time I click. The object look like this:

var item1 = {name: "A", id: 1};

The below toggleFilter method is triggered when I click a checkbox, then dispatch an action from Vuex.

methods: {
            toggleFilter(categoryId) {
                var item1 = {name: "A", id: 1};

                this.$store.dispatch('filter/toggleFilter', item1);
            }
        }

Vuex action:

let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
        let index = state.filters.indexOf(attribute);

        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};

The problem is when I click again the checkbox, it doesn't remove the object from the array, it adds 1 more object into it.

enter image description here

One more weirdness thing is I use the exact above Vuex action for another object, something like this:

methods: {
            toggleFilter(option) {
                option.attributeId = this.attribute.id;
                option.type = 'attribute';

                this.$store.dispatch('filter/toggleFilter', option);
            }
        }

And it works. I don't know why the 1st case doesn't work, but the 2nd case works.

1 Answer 1

1

Every time you create new object var item1 = {name: "A", id: 1};, so indexOf can't not find it. If you item's id is unique, you can try comparing attribute.id

let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
    let index = state.filters.map(item => item.id).indexOf(attribute.id);
        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

There is a find() and a findIndex() method on a JS array, no need to map it. Use state.filters.findIndex(f => f.id == attribute.id) instead.

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.