简体   繁体   中英

How can i add item(obj) to redux state in react

I got an empty array whenever I am trying to add an item(obj). But when I am trying with useState the data is saved in an array but it's not saved along with another item (obj) it just adds the lastest clicked item basically I want to store the item in the state so that it can be used in other components

please correct what I am doing wrong thank you

 const handlecart=(item)=>{
    setCount(count+1)
    const data={name:item.name,image:item.image,price:item.price}
    dispatch(addingToCart(data))
    console.log(cart)
  }

 {localitem.map((product) => (
              <div key={product._id} className="group relative">
                <div className="w-full min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-80 lg:aspect-none">
                  <img
                    src={product.image}
                    alt={"image"}
                    className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                  />
                </div>
                <div className="mt-4 flex justify-between">
                  <div>
                    <h3 className="text-sm text-gray-700 font-semibold">
                      {product.name}
                    </h3>
                  <h4 className="text-base font-medium text-gray-900">
                    Price<p>{product.price}</p> 
                    ${product.price}
                  </h4>
                  </div>

                  <div className="px-3">
                    <button>buy</button>
                    <button onClick={()=>handlecart(product)}>cart</button>
                  </div>
                </div>
              </div>
            ))}

When you look at the return value in the above reducer, you are just overriding the cart in state with a single object. Ideally the cart is a list of items and whenever you add a item to the cart, you need to add it to the existing cart array.

import {
  createSlice
} from "@reduxjs/toolkit";

const initialState = {
  cartItem: [],
}

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addingToCart: (state, action) => {
      const previousCart = [...state.cartItem];
      return {
        ...state,
        cartItem: [...previousCart, action.payload],
      };
    },
  },
});
export default cartSlice.reducer;

export const {
  addingToCart
} = cartSlice.actions;

you can use unwrap to see what's going on, if your action is async. like: dispatch(addingToCart(data)) .unwrap() .then((res) =>{ console.log(res} ) .catch(err => { console.log(err)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM