Home > Software engineering >  Adding objects in pairs to array, how to fix it?
Adding objects in pairs to array, how to fix it?

Time:10-10

When I add an object to the array, the objects I add after the second object are added to the array twice the length of the array.

if(state.favorites.length <= 0) {
    action.payload.checkFavorite = true;
    state.favorites.push(action.payload)
}else {
    state.favorites.map(favorite => {
        if(favorite.product._id === action.payload.product._id) {
            action.payload.checkFavorite = false;
            const newFavorites = state.favorites
                .filter(favorite => favorite.product._id !== action.payload.product._id);
            state.favorites = newFavorites
        }else{
            action.payload.checkFavorite = true;
            state.favorites.push(action.payload);
        }
    })
}

CodePudding user response:

You are assuming if it is not a match, you need to add it. You would be better off using findIndex and removing the index

else {
   // see if it exists
   const index = state.favorites.findIndex(favorite => favorite.product._id === action.payload.product._id);
   // is it in the array
   if (index>=0) {
     action.payload.checkFavorite = false;
     // remove it
     state.favorites.splice(index, 1);
   } else {
     action.payload.checkFavorite = true;
     // add it
     state.favorites.push(action.payload);
   }

}

Now hopefully you are using setState later in your code

CodePudding user response:

Try this

       if ( state.favorites.filter((favorite) => favorite.product._id ===action.payload.product._id ).length === 0) {
           action.payload.checkFavorite = true;
                state.favorites.push(action.payload);
       } else if (tate.favorites.filter((favorite) => favorite.product._id==action.payload.product._id ).length > 0) {
               action.payload.checkFavorite = false;
             const newFavorites = state.favorites.filter(favorite => favorite.product._id !== action.payload.product._id);
                state.favorites = newFavorites
          }
  • Related