I can pass the value of my select-options but I change my mind and want to pass the value first on the button for onClick function.. Thanks
import { useSelector, useDispatch } from "react-redux";
const Purchase = () => {
const products = useSelector(state => state.products);
const dispatch = useDispatch();
const purchaseHandler = e => {
let pName = e.target.options[e.target.selectedIndex].text;
let price = e.target.value;
let obj = { pName, price };
dispatch({ type: "PURCHASE", payLoad: obj });
};
return (
<div>
<select onChange={e => purchaseHandler(e)}>
{products.map((product, index) => {
return (
<option value={product.price} key={index}>
{product.pName} - ${product.price}
</option>
);
})}
</select>
<button onClick={purchaseHandler} className="addToCart">
Add to Cart
</button>
</div>
);
};
export default Purchase;
CodePudding user response:
Save productIndex when selection changes and get the product from products array using index when clicking the button.
Try like below
import { useSelector, useDispatch } from "react-redux";
const Purchase = () => {
const products = useSelector(state => state.products);
const dispatch = useDispatch();
const [productIndex, setProductIndex] = useState(0);
const purchaseHandler = () => {
dispatch({ type: "PURCHASE", payLoad: products[productIndex] });
};
return (
<div>
<select
onChange={e => {
setProductIndex(e.target.value);
}}
>
{products.map((product, index) => {
return (
<option value={index} key={index}>
{product.pName} - ${product.price}
</option>
);
})}
</select>
<button onClick={purchaseHandler} className="addToCart">
Add to Cart
</button>
</div>
);
};
export default Purchase;
