I was building a website using React. It's supposed that there are products that can be added to the cart by clicking "Add to Cart" button.
For now, I am just trying to access each "Add to Cart" button by console logging "action" in the reducer, but only one button among all of them can be triggered.
Code for Product
import {useStateValue} from "./StateProvider"
function Product({id, title, image, price, rating}) {
//accepts props of each product
const [state, dispatch] = useStateValue()
const addToCart = () => {
dispatch({
type: "ADD_TO_CART",
item: {
id: id,
title: title,
image: image,
price: price,
rating: rating
}
})
}
return (
<div className='product'>
<div className="product-info">
<p>{title}</p>
<p className="product-price">
<small>$</small>
<strong>{price}</strong>
</p>
<div className="product-rating">
{Array(rating)
.fill()
.map((_, i) => (
<p></p>
))}
</div>
</div>
<img
src={image}
alt=""
/>
<button onClick={addToCart}>Add to cart</button>
</div>
)
}
Code for StateProvider
import React, {createContext, useContext, useReducer} from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children}) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);
Code for Reducer I was using
export const initialState = {
cart: [],
}
const reducer = (state, action) => {
console.log(action);
switch(action.type) {
case 'ADD_TO_CART':
return{
...state,
cart: [...state.cart, action.item]
}
default:
return state;
}
}
There are 6 products in total ibn my website and none of them except for the last one fires console.log(action) when clicked.
In the main index file, I used this code to import the reducer
import reducer, { initialState } from './reducer';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>
</React.StrictMode>
);
I tried to add a unique value to each product, to correct the z-index but nothing changed. Can someone help me?