In this challenge, you will have to create an application to train what you have learned so far in ReactJS
This will be an application where your main objective is to create a shopping cart hook. You will have access to two pages, a component and a hook to implement the features requested in this challenge:
- Add a new product to the cart;
- Remove a product from the cart;
- Change the quantity of a product in the cart;
- Calculation of the sub-total and total cart prices;
- Inventory validation;
- Display of error messages;
- Among others.
For this challenge, in addition to the concepts seen in class, we will use some new things to make our application even better. So, before going directly to the challenge code, weβll explain a little bit of:
- Fake API with JSON Server;
- Preserve cart data with localStorage API;
- Show errors with toastify.
Just as we use MirageJS in module 2 to simulate an API with transaction data from the dt.money application, we will use JSON Server to simulate an API that has the information of genres and films.
Navigate to the created folder, open it in Visual Studio Code and execute the following commands in the terminal:
yarn
yarn server
Then you will see the message:
Notice that he started a fake API with the resources /stock
and /products
on localhost
on port 3333
from the information in the server.json file located at the root of your project. Accessing these routes in your browser, you can see the return of the information already in JSON:
That way, you just need to consume these API routes normally with Axios.
To preserve the cart data even if we close the application, we will use the localStorage API
This is an API that allows us to persist data in the browser in a key-value scheme (similar to what we have with JSON objects). Since this is a global API, you don't need to import anything before using it.
To save the data, you must use the setItem
method. As a first argument you must enter the name you want to give the registration, in the case of this challenge it is mandatory
to use the name @RocketShoes: cart
. The second argument, on the other hand, is the value of the record that must be in the string
format. Below is an example:
localStorage.setItem('@RocketShoes:cart', cart)
To retrieve the data, you must use the getItem
method, passing as the registration argument which, in the case of this challenge, is mandatory
to use as @RocketShoes: cart
. Below is an example:
const storagedCart = localStorage.getItem('@RocketShoes:cart');
o show the errors on screen, we will use a lib called react-toastify. It helps to show temporary and quick information in a very beautiful way.
Of all the methods, we will only use error
and it will be mandatory to use predefined messages for the tests to pass.
With the template already cloned, the dependencies installed and the fake API running, you must complete where there is no code with the code to achieve the objectives of each test. The documents that must be edited are:
- src/components/Header/index.tsx
- src/pages/Home/index.tsx
- src/pages/Cart/index.tsx
- src/hooks/useCart.tsx
You must receive the cart
array from the hook useCart
and show on screen the number of different products added to the cart. Thus, if the cart has 4 units of item A and 1 unit of item B, the value to be shown is 2 items
.
You must render the products sought from the fake API on screen with the information of title, image, price, quantity added to the cart. Finally, it is necessary to implement the functionality of adding the chosen product to the cart by clicking on the ADD TO CART
button.
In this file, we have three important points to be implemented:
- cartItemsAmount: You must have information about the quantity of each product in the cart. We suggest creating a key/value array using
reduce
where the key represents the product id and the value the quantity of the product in the cart. - loadProducts: You must search for Fake API products and format the price using the
utils/format
helper - handleAddProduct: You must add the chosen product to the cart.
You must render a table with the image, title, unit price, quantity of units and subtotal price of each product in the cart. In addition, it is also necessary to render the total price of the cart. Finally, it is necessary to implement the functionalities of the buttons to decrement, increase and remove the product from the affection.
In this file, we have five important points to be implemented:
- cartFormatted: You must format the cart by adding the fields
priceFormatted
(price of the product) andsubTotal
(price of the product multiplied by the quantity) both properly formatted withutils/format
. - total: You must have information about the total value of the cart properly formatted with
utils/format
. - handleProductIncrement: You must increase the quantity of the product chosen in the cart by 1 unit.
- handleProductDecrement: The quantity of the product chosen in the cart must be reduced by 1 unit, where the minimum value is 1 (in this case the button must be deactivated).
- handleRemoveProduct: You must remove the chosen product from the cart.
Although it does not directly return any rendering of elements in the interface like the other files, this is the heart of the challenge. He is responsible for:
- hook
useCart
; - context
CartProvider
; - manipulate
localStorage
; - display
toasts
.
So this is where you will implement the features that will be used by the rest of the app. The main points are:
-
cart: You should check if there is any record with the value
@RocketShoes: cart
and return this value if it exists. Otherwise, return an empty array. -
addProduct: You must add a product to the cart. However, there are a few things to check
-
The updated value of the cart must be perpetuated in localStorage using the
setItem
method. -
If the product already exists in the cart, you should not add a new repeated product, just increase the quantity by 1 unit;
-
Check if the desired quantity of the product is in stock. Otherwise, use the
error
method of react-toastify with the following message:
toast.error('Quantidade solicitada fora de estoque');
- Capture the errors that occur along the method using
trycatch
and, in catch, use theerror
method of react-toastify with the following message:
toast.error('Erro na adição do produto');
-
removeProduct: You must add a product to the cart. However, there are a few things to check:
-
The updated value of the cart must be perpetuated in localStorage using the
setItem
method. -
Capture the errors that occur along the method using
trycatch
and, in catch, use theerror
method of react-toastify with the following message:
toast.error('Erro na remoção do produto');
-
updateProductAmount: You must add a product to the cart. However, there are a few things to check:
-
The updated value of the cart must be perpetuated in localStorage using the
setItem
method. -
If the product quantity is less than or equal to zero, exit the updateProductAmount function instantly.
-
Check if the desired quantity of the product is in stock. Otherwise, use the
error
method of react-toastify with the following message:
toast.error('Quantidade solicitada fora de estoque');
Catch the errors that occur along the method using trycatch
and, in catch, use the error
method of react-toastify with the following message:
toast.error('Erro na alteração de quantidade do produto'');
This project is under a license MIT.
Challenge proposed with π by Rocketseat π Join this great community!