skip to Main Content

This is my index.js file in cart folder for cart page

import React from "react";
import { Link } from "react-router-dom";
import CartProducts from "./CartProducts";
import Layout from "../../components/Layout";
import { useCart } from "../../hooks/useCart";
import { formatNumber } from "../../helpers/utils";
import { v4 as uuid } from 'uuid';

const Cart = () => {
  const { total, cartItems, itemCount, clearCart, checkout, handleCheckout } =
    useCart();
   

    const handleClick = async (itemCount, total) => {
        const uniqueId = uuid();
        let response = await fetch("http://localhost:5000/", {
          method: "post",
          body: JSON.stringify({ uniqueId, itemCount, total }),
          headers: {
            "Content-Type": "application/json",
          },
        });
      
        if (response.ok) {
          try {
            const result = await response.json();
            console.warn(result);
            if (result) {
              alert(
                "Order Placed for " +
                  itemCount +
                  " Total amount to be paid on delivery " +
                  total
              );
            }
            handleCheckout();
          } catch (error) {
            console.error("JSON parsing error:", error);
          }
        } else {
          const errorMessage = await response.text(); // Parse the response as plain text
          console.error(errorMessage); // Log the error message
          // Handle the error message in your application as needed
        }
      };
      
      
  return (
    <Layout title="Cart" description="This is the Cart page">
      <div>
        <div className="text-center mt-5">
          <h1>Cart</h1>
        </div>
        <div className="row no-gutters justify-content-center">
          <div className="col-sm-9 p-3">
            {cartItems.length > 0 ? (
              <CartProducts />
            ) : (
              <div className="p-3 text-center text-muted">
                Your cart is empty
              </div>
            )}
            {checkout && (
              <div className="p-3 text-center text-success">
                <p>Checkout successfull</p>
                <Link
                  to="/"
                  className="btn btn-outline-success btn-sm"
                  onClick={clearCart}
                >
                  BUY MORE
                </Link>
              </div>
            )}
          </div>
          {cartItems.length > 0 && (
            <div className="col-sm-3 p-3">
              <div className="card card-body">
                <p className="mb-1">Total Items</p>
                <h4 className=" mb-3 txt-right">{itemCount}</h4>
                <p className="mb-1">Total Payment</p>
                <h3 className="m-0 txt-right">{formatNumber(total)}</h3>
                <hr className="my-4" />
                <div className="text-center">
                  <button
                    type="button"
                    className="btn btn-primary mb-2"
                    onClick={() => {
                      handleClick(itemCount, total);
                    }}
                  >
                    CHECKOUT
                  </button>
                  <button
                    type="button"
                    className="btn btn-outlineprimary btn-sm"
                    onClick={clearCart}
                  >
                    CLEAR
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
};

export default Cart;

and this is my cartContext.js file in cart folder

import React, { createContext, useReducer } from "react";
import { CartReducer, sumItems } from "./CartReducer";


export const CartContext = createContext();
const storage = localStorage.getItem("cart")
  ? JSON.parse(localStorage.getItem("cart"))
  : [];
const initialState = {
  cartItems: storage,
  ...sumItems(storage),
  checkout: false,
};


const CartContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(CartReducer, initialState);

  const increase = (payload) => {
    dispatch({ type: "INCREASE", payload });
  };

  const decrease = (payload) => {
    dispatch({ type: "DECREASE", payload });
  };

  const addProduct = (payload) => {
    dispatch({ type: "ADD_ITEM", payload });
  };

  const removeProduct = (payload) => {
    dispatch({ type: "REMOVE_ITEM", payload });
  };

  const clearCart = () => {
    dispatch({ type: "CLEAR" });
  };

  const handleCheckout =  () => {
    console.log("CHECKOUT", state);
    dispatch({ type: "CHECKOUT" });
  };
  const contextValues = {
    removeProduct,
    addProduct,
    increase,
    decrease,
    clearCart,
    handleCheckout,
    ...state,
  };
  return (
    <CartContext.Provider value={contextValues}>
      {children}
    </CartContext.Provider>
  );
};

export default CartContextProvider;

and this is my index.js file in backend folder

const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority').catch(error => console.log(error));


// Schema for users of app
const orderSchema = new mongoose.Schema({
    orderNumber:{
        type: Number,
        unique: true,
        required: true
    },
    items: {
        type: Number,
        required: true,
    },
    totalAmt: {
        type: Number,
        required: true,
    },
    date: {
        type: Date,
        default: Date.now,
    },
});
const Order = mongoose.model('orders', orderSchema);
Order.createIndexes();

// For backend and express
const express = require('express');
const app = express();
const cors = require("cors");
console.log("App listen at port 5000");
app.use(express.json());
app.use(cors());
app.get("/", (req, resp) => {

    resp.send("App is Working");
    // You can check backend is working or not by 
    // entering http://loacalhost:5000
    
    // If you see App is working means
    // backend working properly
});

app.post("/", async (req, resp) => {
    try {
        const { uniqueId, itemCount, total } = req.body; // Destructure the data from the request body
        const order = new Order({ orderNumber: uniqueId, items: itemCount, totalAmt: total });
        let result = await order.save();
        result = result.toObject();
        if (result) {
          resp.send(req.body);
          console.log(result);
        } else {
          console.log("Order already Placed Successfully");
        }
      } catch (e) {
        resp.send("Something Went Wrong");
      }
});
app.listen(5000);


The database is connecting successfully but when I try to send data to database it is not going same error occuring again and again. I try to make changes in code nothing workout.

2

Answers


  1. I am guessing that line 38 of your index.js is const result = await response.json();? if so, then your backend is responding an invalid JSON which .json() will try to parse into a JS object. It will throw an error if so. If I am not mistaken, check resp.send(req.body); if it’s really responding the right way or check any characters in your response data which might break the response.

    Login or Signup to reply.
  2. You need send a JSON response back to your user because your fetch request is doing an await response.json(); so if your POST fails you still want to send a JSON back. At the minute you are sending a string back. Update like this:

    app.post("/", async (req, resp) => {
       //...
       //...
          } catch (e) {
            console.log(e);
            resp.status(500).json({message: "Something Went Wrong"});
          }
    });
    

    With console.log(e) you will also be able to see what the actual error was.

    Your const errorMessage = await response.text(); never gets fired because your if(response.ok) will always be true when the status code in the range 200-299. By sending a 500 in my example you then need to do:

    } else {
        const errorMessage = await response.json(); // Parse the response as json text
        console.error(errorMessage); // Log the error message
              // Handle the error message in your application as needed
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search