Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!