We wrote an API handler for adding a new cart item.
Now we want to create the user interface to allow
our customers to add a product to their cart.
As I mentioned a few times before,
on each product page we want to show
a button saying "Add to cart".
But we also want to let the user select a quantity,
so we could display an input field
where to enter a number.
Incidentally, at this point we can delete
all the cart items that we created
just to have some initial data
to display in the cart page.
The user will be able to add items from our website.
If we look at the code,
you'll need to modify the Product page.
And I suggest creating a separate React component
for the "Add to cart" feature,
because we need to combine a numeric field
for the quantity
with a button to submit the API request.
I would call this component "AddToCartWidget".
Also, you should only display this component
if the user is signed in.
Let me show you what the page should look like.
Here's the quantity field
and the "Add to cart" button.
Now, for this challenge you don't need to
actually make the API request.
We'll do that in a separate step.
For now, when the user clicks the button
we just want log a message to the console
printing the "productId" and the "quantity"
that should be added to the cart.
The quantity field should be
a numeric "input" element
so that the user can easily change its value.
And you'll need to keep track of that value
in the component state,
so you can log it when the button is clicked.
That's your challenge for this video.
Go ahead and do it!
Ok, it's time to show you my solution.
I have created a new React component
called "AddToCartWidget".
Here I define a state variable for the quantity,
with an initial value of 1.
And this is bound to an "input" element
of type "number".
Note that the element value is always a string,
but the state variable is a number,
so we need to convert the value back and forth.
Then this component also displays a button,
that says "Add to cart".
And this is using our existing Button component,
but I had to add the "onClick" prop here,
because we didn't need it before.
Now, when the user clicks the button
we execute this function
where for now I'm simply logging
the "productId" and "quantity" values.
Note that we expect the "productId"
to be passed in the props to this component.
In fact, if we go and look at the ProductPage,
here I'm first calling our "useUser" hook
to get the user details,
because we only want to display
the "AddToCartWidget" if "user" is set.
And when displaying the AddToCartWidget
I'm passing the "product.id" down as a prop.
That's it. In the next video we'll take care
of actually making the API request.