Question:
How to add product to favorite screen without an error?

Array splice and push methods mutate the existing array reference. Create shallow copies then overwrite. In this case if you would like to remove an element then filter the current state, and when adding an element concatenate. Make sure you are updating and returning the correct state properties.


Example:

const reducer = (state = initialState, action) => {

  switch(action.type) {

    case 'ADD_PRODUCT_TO_FAVORITE':

      const product = action.payload;


      const index = state.FavoritesList.findIndex(

        (item)=> item?.id === product?.id

      );


      if (index !== -1) {

        return {

          ...state,

          products: state.FavoritesList.filter((_, i) => i !== index),

        };

      } else {

        return {

          ...state,

          products: state.FavoritesList.concat(product),

        };

      }


    case 'CLEAR':

      return { ...state, cart: [], FavoritesList: [] };

           

    default:

      console.log("unhandled action", { action });

      return state; // <-- just return current state

  }

};


Suggestion:

Instead of double-storing the product data, the "favorited" products should store just the product id. You can get back the complete favorites array derived from the products array filtered by products with a favorited id.


Example:

const initialState = {

  products: ProductData,

  cart: [],

  favorites: {},

};


const reducer = (state = initialState, action) => {

  switch(action.type) {

    case 'ADD_PRODUCT_TO_FAVORITE':

      const product = action.payload;


      return {

        ...state,

        favorites: {

          ...state.favorites,

          [product.id]: !state.favorites[product.id],

        },

      };


    case 'CLEAR':

      return { ...state, cart: [], favorites: {} };

           

    default:

      console.log("unhandled action", { action });

      return state; // <-- just return current state

  }

};


const { favorites, products } = useCart();


const favoritesList = products.filter(product => favorites[product.id]);


Answered by: >Drew Reese

Credit:> StackOverflow


Suggested blogs: 

>How you can send email from a shared inbox in Python

>How to read frame from ffmpeg subprocess in Python?

>What are the steps to fix error while downloading PDF file- Python

>Invoking Python script from scons and pass ARGLIST

>How to save python yaml and load a nested class?-Python


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.