Software Development

How to create a product page using CS-Cart API in NextJs


Good morning guys, today in this blog we will see all about api integration in cs-cart product detail page with upcoming js so hope this blog will be interactive for you so without further ado , let’s start

Presentation of the CS basket: CS-Cart is a popular e-commerce platform that allows businesses to create and manage online stores. It offers a range of features for creating product catalogs, processing payments, order management, and more. One of CS-Cart’s main strengths is its flexibility, which includes an API allowing developers to extend and customize the platform’s functionality.

So here we will learn how to create a product page and we will also see how to integrate the API into it. Our main concern is functionality, so apart from CSS design, if you want to create a good UI, you can choose whichever one you want. Dependencies.

Creating a product page using the CS-Cart API in Next.js:

In this comprehensive guide, we’ll explore how to create a product page using the CS-Cart API in a Next.js application. We’ll break the process into several steps, providing code examples and explanations along the way.

Step 1: Project Setup – In the first step, you need to configure this project. You can follow this blog about next project setup which covers everything about next js project setup.

Configuring Global Variables – We would have set up a few global variables which we can configure in our next one. config file this way, but if you want to use env you can also use that, it’s entirely up to you

module.exports = {
  env: {
    apiUrl: 'YOUR_CS_CART_API_URL_HERE',
    apiKey:'YOUR_API_KEY_HERE'
  },

Step 2: Install dependencies and configuration of global variables – In this step you can install all the species necessary for your project. In my case we just need tailwinds for the basic design.

Step 3: Create a component for the product page – Inside of pages directory of your Next.js project, create a new file called Index.js. This file will contain the component code for your product page

import React, { useEffect, useState } from "react";

export default function ProductPage() {

  const (isLoading, setLoading) = useState(true);
  const (data, setData) = useState(null);
  useEffect(() => {
    const apiUrl = process.env.apiUrl;
    const apiKey = process.env.apiKey;

    fetch(apiUrl, {
      headers: {
        Authorization: `Bearer ${apiKey}`,
      },
    })
      .then((response) => {
        setLoading(false);
        setData(json.response(response.data));
      })
      .catch((error) => {
        console.error("Error fetching product data:", error);
        setLoading(false);
        setData(null);
      });
  }, ());

  const ProdcutDetail = (props) => {
    const data = props?.props || null;
    return (
      <React.Fragment>
        <div className="mt-6">
          <div classname="lg:px-24 md:px-12 px-3">
            <div className="container mx-auto px-4">
              <div className="lg:col-gap-12 xl:col-gap-16 mt-3 grid grid-cols-1 gap-12 lg:mt-12 lg:grid-cols-5 lg:gap-16">
                <div className="lg:col-span-3 lg:row-end-1">
                  <div className="lg:order-2 ">
                    <div className="max-w-xl overflow-hidden rounded-lg">
                      <Image
                        className="h-(70vh)"
                        src={data?.main_pair?.main}
                        width={500}
                        height={230}
                        priority={true}
                        alt="loading"
                      />
                    </div>
                  </div>
                </div>
                <div className="lg:col-span-4 lg:row-span-2 lg:row-end-2">
                  <h1 className="sm: text-2xl font-bold text-gray-900 sm:text-3xl">
                    {data?.product}
                  </h1>
                  <div className=" mt-3">
                    <p className=" text-sm font-medium text-gray-500">
                      In Stock : {data?.max_qty}
                    </p>
                  </div>
                  <h2 className="mt-3 text-base text-gray-900">Details </h2>
                  <div className="mt-3  flex select-none flex-wrap items-center gap-1">
                    <section>
                      <p
                        dangerouslySetInnerHTML={{
                          __html: data?.full_description,
                        }}
                      ></p>
                    </section>
                  </div>

                  <div className="mt-10 flex flex-col items-center justify-between space-y-4 border-t border-b py-4 sm:flex-row sm:space-y-0">
                    <div className="flex items-end">
                      <h1 className="text-3xl font-bold">
                        ${parseFloat(data.price)}
                      </h1>
                    </div>
                    <button
                      type="button"
                      className="inline-flex items-center justify-center rounded-md border-2 border-transparent bg-gray-900 bg-none px-12 py-3 text-center text-base font-bold text-white transition-all duration-200 ease-in-out focus:shadow hover:bg-gray-800"
                    >
                      <svg
                        xmlns="
                        className="shrink-0 mr-3 h-5 w-5"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"
                        />
                      </svg>
                      Add to cart
                    </button>
                  </div>
                  <ul className="mt-8 space-y-2">
                    <li className="flex items-center text-left text-sm font-medium text-gray-600">
                      <svg
                        className="mr-2 block h-5 w-5 align-middle text-gray-500"
                        xmlns="
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                          className
                        />
                      </svg>
                      Free shipping worldwide
                    </li>
                    <li className="flex items-center text-left text-sm font-medium text-gray-600">
                      <svg
                        className="mr-2 block h-5 w-5 align-middle text-gray-500"
                        xmlns="
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
                          className
                        />
                      </svg>
                      Cancel Anytime
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  };
  
  return (
    <div>
      {isLoading ? (
        "Loading"
      ) : data ? (
        <React.Fragment>
          <ProdcutDetail props={data} />
        </React.Fragment>
      ) : (
        "No data available"
      )}
    </div>
  );
}

The output will look like the image below

screenshot_1694608092341

In this code:

  • We import React and other necessary libraries.
  • We used tailwindcss to ProdcutDetail style product detail component.
  • We display product information once loaded.

Step 4: Configure API Authentication – To access the CS-Cart API, you will need to configure authentication. Typically, CS-Cart uses API or OAuth 2.0 tokens for authentication. Consult your CS-Cart API documentation or settings to obtain the necessary authentication information.

Once you have the credentials, you can edit the recovery request in the useEffect to include authentication headers:

useEffect(() => {
  const apiUrl = process.env.apiUrl;
  const apiKey = process.env.apiKey;
  fetch(apiUrl, {
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  })
    .then((response) => {
      setProduct(response.data);
    })
    .catch((error) => {
      console.error('Error fetching product data:', error);
    });
}, ());

Step 5: Run your Next.js application To see your product page in action, run your Next.js application:

npm run dev

This command will start the development server and you will be able to access your site at http://localhost:3000.

If you encounter problems, use the browser developer tools and console to debug your code. Check your API authentication, network requests, and error handling.

Conclusion: In this guide, we created a product page in a Next.js application that retrieves product data from the CS-Cart API. We covered setting up the development environment, creating a component, setting up authentication, styling, routing, testing, and deployment of the API.

By following these steps and customizing them to suit your CS-Cart store and design requirements, you can create a dynamic, interactive product page that integrates seamlessly with your CS-Cart e-commerce platform.



Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button