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
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)