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

307
Visualizações
REDUX: How can I delete related item from my array?

I am working on a project in React using Redux. I am trying to delete an item. However, it added an array to my array. How can I delete it? Here is my code:

import ActionTypes from "../constants/ActionTypes";

const initialState = {
  myCities: [],
  aCity: {},
  getCityById: {},
};

export const WeatherReducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case ActionTypes.GETBY_CITYNAME:
      return {
        ...state,
        aCity: payload,
        myCities: [...state.myCities, payload],
      };
    case ActionTypes.GETCITYBYID:
      return {
        ...state,
        getCityById: payload,
        myCities: [], //first I tried to it empty, not works at all and I also tried without it
        myCities: [ 
          ...state.myCities,
          initialState.myCities.filter((item) => item.id !== payload.id), //Then I tried to find related item, choose it and add all objects to my array without related item
        ],
      };
    default:
      return state;
  }
};

I also added my delete stuff:

const HandleDelete = (cityId) => {
  dispatch(GetCityById(cityId, apiKEY));
};

Thanks for your effort

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The .filter() method already returns a new array, so there is no need to put it inside of another array here

myCities: [ 
  ...state.myCities,
  initialState.myCities.filter((item) => item.id !== payload.id)
],

The above creates a new array [], and then puts all the elements in state.myCities into that new array using the spread syntax (...). Then, it adds a new element, which is the filtered array of initialState.myCities.filter(). Instead, as .filter() returns an array only containing the items your callback returned true for, you can directly use that array as the new value for myCities:

myCities: initialState.myCities.filter((item) => item.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