Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda