How to push the product data to data layer in REACT?
I have multiple products on a page with an add to cart button next to each, my ultimate goal is to achieve a checkout page. First step is to push the product data to data layer. My data is coming from a Firebase database.
This is my reducer:
export const initialState = {
basket: [],
};
const reducer = (state, action) => {
console.log(action);
switch (action.type) {
case 'ADD_TO_BASKET':
return {
...state,
basket: [...state.basket, action.item],
};
default:
return state;
}
};
export default reducer;
This is the state provider:
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);
And this is where I need help to write the dispatch code, my current code is throwing errors in item:
import React, { MouseEventHandler } from "react";
import "./product.scss";
import placeholder from "./../../../../assets/images/productPlaceholder.jpg";
import { AdvertiseStoreProduct } from "../../../../models/AdvertiseStore/advertiseStore.model";
import { privateDecrypt } from "crypto";
import { useStateValue } from '../../../../StateProvider';
interface ProductProps {
index: number;
clicked: MouseEventHandler;
product: AdvertiseStoreProduct;
}
const Product = (props: ProductProps) => {
const { product, clicked, index } = props;
const [state, dispatch] = useStateValue();
const addToBasket = () => {
//dispatch product to data layer
dispatch({
type: 'ADD_TO_BASKET',
item: {
product.id: product.id,
product.name: product.name,
product.price: product.price,
},
});
};
return (
<div className="product-card" onClick={clicked}>
<div className="product-card-image">
<img
src={product.imageUrl || placeholder}
alt={product.name}
/>
</div>
<div className="product-card__details">
<h5 className="product-card--name">{product.name}</h5>
<p className="product-card--price"> ₹ {product.price}</p>
<div><button onClick={addToBasket}>Add to cart</button></div>
</div>
</div>
);
};
export default Product;
Solution 1:
I guess the way you are assigning object is wrong.
item: {
"keyName": value
}
or u want a dynamic key name use
item: {
[variableName]: value
}
dispatch({ type: 'ADD_TO_BASKET', item: {
(wrongkey) product.id: product.id, product.name: product.name, product.price: product.price, }, });