How to Create a Cart State using NextJS15

Updated at: 12 Feb 2025Deepak Painkra
 

In this article, I will create a cart state using NextJS15. Also, you could use the redux toolkit, but we will be using NextJS only.

Let's get into the tutorial while issuing these commands,

 
npx create-next-app@latest
 

Creating a Function

After creating the next app, create an actions folder inside the app directory. Now, create an actions.js file inside the actions folder.

Now, let's create an export function named addToCart to set the item onto the localstorage of a browser and write this code inside the actions.js file,

export const addToCart = (product) => {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')

    const existingProductIndex = cart.findIndex(item => item._id === product._id)

    if(existingProductIndex > -1) {
        cart[existingProductIndex].inventory += 1
    }
    else {
        cart.push({
            ...product, inventory: 1
        })
    }

    localStorage.setItem('cart', JSON.stringify(cart))
}
 

You could also add some functionality while adding more functions, for instance, updating and removing the item.

Now, let's create another export function named Get to the Cart. We will be using this function to get products from the localstorage

 //actions.js
 export const getCartItems = () => {
    return JSON.parse(localStorage.getItem('cart') || '[]')
}
 

Creating a Product Page

Now, let's create a shoe page inside the app directory. Create page.js inside the shoe page. Import the action file we created, along with importing estate and effect for fetching the product.

"use client";
import React, { useState, useEffect } from "react";
import { addToCart } from "../../actions/actions";

export default function Page() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch("http://127.0.0.1:8000/api/productlist/");
        const data = await response.json();
        const results = data.results || [];

        setProducts(results);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);


  const handleAddToCart = (e, product) => { 
    e.preventDefault();
    addToCart(product);
    console.log(product)
    if(product){
        
        alert(`${product.title} added to the cart`); 
      } else {
        alert("Please select a variant", "error"); 
      }
  };
  

  return (
    <div>
     {
        products.map((product) =>(
            <div key={product._id}>
                <p>{product.title}</p>
                <p>{product.price}</p>
                <button onClick={(e)=>handleAddToCart(e, product)}>
                   addToCart
                </button>
            </div>

            
        ))
     }
    </div>
  );
}

Also, we need to create a function to handle the addToCart function, and you could add some toast notifications for confirmation.

After fetching the data, we need to map the products. If you don't have a product api. You can create a demo product list like this one,

 const products = [{
"id": "1,"
"title" : "Red Tshirt",
"desc" : This a red Tshirt"
}])}

 

Creating a Cart Page

In this cart, let's import the get to cart function, which we have created on the actions page.

After importing the function, map the product, and since I have variation in my API, this is how we can get the product from the local storage. We are using the use effect to set the product.

import React from 'react'
import { useState, useEffect } from 'react'
import { getCartItems, addToCart } from '@/app/actions/actions'


const CartPage = () => {

  const [cartItems, setCartItems] = useState([]);

  useEffect(()=>{
    setCartItems(getCartItems());

  }, []);

{cartItems.length === 0 ? (
      <p>Your cart is empty.</p>
    ) : (
      cartItems.map((item) => (
        <div key={item.id} style={{ borderBottom: "1px solid #ddd", padding: "10px", marginBottom: "10px" }}>
          <p><strong>Product:</strong> {item.title}</p>
          <p><strong>Price:</strong> ₹{item.price}</p>
          <p><strong>Description:</strong> {item.product_desc}</p>
              ))
            ) : (
              <p>No variations available.</p>
            )}
          </div>
        </div>
      ))
    )}

}

There we go. We have successfully created an add-to-cart functionality and cart state

Support Us

Your support helps us continue our work. Please consider making a donation.

Donate with PayPal