Open V-FOR-VEND3TTA opened 12 months ago
For a deeper dive into building applications this way, look into server-side rendering and static site generation. Pre-generating your product list and detail pages will be immensely useful for improving your search engine optimization. React libraries such as Gatsby and Next.js help you to do this. Check out the Commerce.js Community Guides section for more guides using these tools!
Commerce.js was built with all the frontend functionality needed to build a complete eCommerce store. Simply make requests to various Chec API endpoints, receive successful responses, then use the raw data to output beautifully onto your web store.
You can now start to make requests to fetch data from Chec to list your product data.
commerce.products.list()
. This request would make a call to theGET v1/products
API endpoint and return a list of product data. Open up yourApp.js
file and delete the code that came with creating a new React app and we will write this file from scratch.Let's get to writing out our first functional component in
App.js
. Import commerce as well as a new module,useState
which is the first React hook we'll be using to make our function component stateful. The first two API endpoint we will want to work with is the Products and Merchant endpoint. The Products endpoint will allow us to work with data such as the product name, product price, product description etc. The Merchant endpoint will contain information such as the e-commerce business name and contact details.After the opening of our App function, we need to destructure and return products and a method setProducts from the function useState. useState returns a tuple, which is an array with two items, in this case an initial value and a function that will update that value. The argument we will pass in to useState is the initial value of an empty array to be able to store the product data in it when we fetch the data. We follow the same pattern for the Merchant value, but instead we will pass in an empty object as an argument to useState.
💡 Tip
useState allows us to make function components stateful. This means that the components has the ability to keep track of changing data. You might ask why would be want to keep track of changing data. Any commerce store needs to have the ability to update its products listing in real-time. Be it new products being added, products being sold out, or products being taken off. The API data constantly will get updated, therefore the UI has to be reactive.
You can now make your first Commerce.js request! Create a function called fetchProducts() in the component and make a request to the products endpoint using the Commerce.js method commerce.products.list().
Inside the function, we use the commerce object to access the products.list() method for access to product data. commerce.products.list() is a promise-based function call that will resolve the request and then() sets the response data with setProducts into the products state key created earlier. In Chec, product is returned in an object called data, which is why we set the response as product.data. The catch() method catches any errors in the case that the request to the server fails.
Of course simply creating the functions do not do anything as you have yet to call them. When the app component mounts to the DOM, we will use our next React hook useEffect() to call the fetching of data. It is a React lifecycle hook also known as side effects, that helps to call functions after the component first renders to the DOM and also anytime the DOM updates. Since we are loading data from a remote endpoint, we want to invoke the fetchProducts() function to update the state with the returned products so that we can render our updated data.
First import useEffect from React in our import statement at the very top import React, { useState, useEffect } from 'react';.
Then we can use the function like so:
Above, we pass in our effect as a function fetchProducts() and also by leaving the second argument array empty, this method will run once before the initial render.
With returned product data object containing all the property endpoints such as the product name, the product description, product price or any uploaded variants or assets. This data is exposed when you make a request to the API. As mentioned above, Commerce.js is a Software Development Kit(SDK) that comes with abstracted axios promise-based function calls that will help to fetch data from the endpoints. The public key access that we briefed over above is a public token key from a merchant store. This account already has products and products information uploaded to the Chec dashboard for us to run a demo store with. You now go back to App.js and include the ProductsList component.
prop-types
library to do so.Now lets create a component ProductItem.js and start by creating a function component and name it ProductItem. This component will render the individual product card. We then pass in the product parameter which the parent component will parse out as each individual product item. You will reference this property to access each product's image, name, description, and price via .image.url, .name, .description and .price in the return statement.
Product descriptions return HTML. To strip HTML from the product description string, using this string-strip-html handy library will do the trick. Install this library by running yarn add string-strip-html or npm i string-strip-html. After installing, import the module in and pass in the product description to the stripHtml function.
If you look at the returned data in your products request, the data object comes with all the information that you need to build a product listing view. In the code snippet above, your product prop is being used to access the various properties. First, render an image tag with the src value of product.image?.source as the values inside the curly braces dynamically binds to the attributes.
First, import in the ProductItem component. Next, define a products prop. This will be provided by the parent component.
In your return statement you need to use the map function to render a ProductItem component for each product in your products prop. You also need to pass in a unique identifier (product.id) as the key attribute - React will use it to determine which items in a list have changed and which parts of your application need to be re-rendered.
This component will be a bit bare-boned for now except for looping through a ProductItem component.
With both your product item and list components created, go back to App.js to render the and pass in the products prop with the returned product data as the value. This means that the value of the ProductsList component's prop products will be resolved from the parent (App) component's state, and will update automatically whenever it changes.
Your final App.js component should look like the above code block. If you want to build in a loading state while your products load, you could add loading: true to your initial state, have fetchProducts() change this to false when the promise resolves, and add something like this to your component:
That wraps it up! Awesome, you've just wrapped up creating a products listing page using Commerce.js and React!