...
/Creating the Storefront, Cart, and Product Detail Pages
Creating the Storefront, Cart, and Product Detail Pages
Learn to create different components of an e-commerce app with Chakra UI and Next.js.
GraphCMS offers a well-made, rock-solid, open-source template for creating e-commerce websites. We’re not adopting this starter template because we want to fully understand the reasoning behind certain technical decisions and how to approach the problems that can appear during the development phase.
Building the storefront
We can now focus on developing the first essential components for our storefront. We’ll wrap our entire application in a Chakra UI box so that every page will have a similar layout. We can do that by opening the _app.js
file and adding the following components:
import { Box, Flex, ChakraProvider } from '@chakra-ui/react';function MyApp({ Component, pageProps }) {return (<ChakraProvider><Flex w="full" minH="100vh" bgColor="gray.100"><Box maxW="70vw" m="auto"><Component {...pageProps} /></Box></Flex></ChakraProvider>);}export default MyApp;
Fetch and display the products
Now, we can start thinking about how we want to show our products on the home page. However, before doing that, we may want to check the data provided via GraphQL APIs by the CMS, and we can easily do that by going into the “API Playground” section of our dashboard. Here, we can write our GraphQL queries, taking advantage of the Explorer functionality to help us create highly customizable GraphQL queries with ease.
In the query shown in the preceding screenshot, we’re retrieving all the publicly available products. We can use this exact query in our Next.js app, so let’s create a new /lib/graphql/queries/getAllProducts.js
file and add the following content:
import { gql } from 'graphql-request';export default gql`query GetAllProducts {products{idnameslugpriceimages{idurl}}}`;
We’re now ready to fetch all the products to populate our home page. To generate a static page at build time, let’s head to our pages/index.js
page and retrieve the products inside the getStaticProps
function:
import graphql from '../lib/graphql';import getAllProducts from '../lib/graphql/queries/getAllProducts';export const getStaticProps = async () => {const { products } = await graphql.request(getAllProducts)return {props: {products,},};};
At this point, we might be wondering how to handle cases where we create a new product and want to display it immediately on the home page. Here, we have two options:
Use
getServerSideProps
instead ofgetStaticProps
, which will dynamically generate the page on each request, but we already know its downsides.Use incremental static regeneration so that after a given period, the page gets regenerated, including any new API changes.
We’ll proceed with the second option by adding the following ...