Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
Redux toolkit filter() not working when wanting to display new array at the same time

I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.

so I've made a Slice for cart in redux. the 'addProduct' part works fine, but the 'deleteProduct' reducer which uses filter() doesn't work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)

my slice:

const selectedProductsSlice = createSlice({
    name:'selectedProducts',
    initialState:{
        productList:[],
        checkoutPrice:0,
    },
    reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
}});

my button and handleDelete:

<button className="btn-delete" onClick={handleDelete(product)}>Delete</button>

  function handleDelete(p) {
    console.log(p)
    dispatch(deleteProduct(p.product))
  }

edit: filter didnt work in every possible way i tried. so i changed my way and did this instead to work. but still i wonder why didnt filter() method work properly.

        deleteProduct: (state, { payload }) => {
            const foundIndex = state.productList.findIndex((p) => {
                return p.product.id === payload.id
            })
            state.productList.splice(foundIndex,1)
   
        }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The filter operation creates a new array without changing the existing instance. Therefore you need to assign it to state.

deleteProduct: (state, { payload }) => {
    return {
        ...state,
        productList: state.productList.filter(
            foundProduct => foundProduct.id !== payload.id
        )
    };
};

You also need to change the way you call the handleDelete in the onClick handler.

onClick={() => handleDelete(product)}
about 4 years ago · Juan Pablo Isaza Relatório

0

I went through exactly same problem as you. I solved this problem just to move my reducer to another existing reducer
Hope you to get through it. I couldn't pass it by

about 4 years ago · Juan Pablo Isaza Relatório

0

Filter methods returns new array so you have to update your existing array tool. Please update your slice:

const selectedProductsSlice = createSlice({
        name:'selectedProducts',
        initialState:{
        productList:[],
        checkoutPrice:0,
        },
        reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList=state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
    }});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda