Add to Cart Item functionality is not working in my react-redux

Viewed 247

I've been working on React-django shopping Cart project and my add to cart functionality is not working.I have tried alot but not sure where i am doing wrong I'm working on react shopping cart using react-redux and My add to cart Functionality is not working. I've tried a lot with multiple approaches but those did not work. I'm unable to get data into my CartItem. Did stack over flow tried multiple things but still not worthy.

this is my CartActions.js

import React from "react";
import axios from "axios";

import { ADD_CART_ITEM } from "../constant/cartConstant";

const addToCart = (id, qty) => async (dispatch, getState) => {
  const { data } = await axios.get(`/http://127.0.0.1:8000/products/${id}`);

  console.log(data, "<<<<<<DATA");
  dispatch({
    type: ADD_CART_ITEM,
    payload: {
      product: data.id,
      name: data.name,
      image: data.image,
      price: data.price,
      countInStock: data.countInStock,
    },
  });
  localStorage.setItem(
    "cartItems",
    JSON.stringify(getState().CartReducer.cartItems)
  );
};
export default addToCart;

this is my Cart.js

import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux'
import addToCart from '../actions/CartActions'

function Cart() {
    const { id } = useParams();
    const { search } = useLocation();

    const ProductID = id;


    const qty = search ? search.split("=") : 1
    console.log(qty, ">>>QTY");
    const dispatch = useDispatch()
    console.log(ProductID, ">>>>PROduct ID");

    useEffect(() => {
        if (ProductID) {
            dispatch(addToCart(ProductID, qty))
        }
        console.log("Hello world");
    }, [dispatch, ProductID, qty])
    return (
        <div>Cart</div>
    )
}

export default Cart

this is my CartReducer.js

import React from "react";

import { ADD_CART_ITEM } from "../constant/cartConstant";

function cartReducer(state = { cartItems: [] }, actions) {
  switch (actions.type) {
    case ADD_CART_ITEM:
      const Item = actions.payload;
      const exitsItem = state.cartItems((x) => x.product === Item.product);
      if (exitsItem) {
        return {
          ...state,
          cartItems: state.cartItems.map((x) =>
            x.product === exitsItem.product ? Item : x
          ),
        };
      } else {
        return {
          ...state,
          cartItems: [...state.cartItems, Item],
        };
      }

    default:
      return state;
  }
}

export default cartReducer;

I have tried multiple approaches but those did not help me

1 Answers

Your API call URL has an unexpected forward-slash ('/') in the beginning.

Correct Pattern.

const { data } = await axios.get(`http://127.0.0.1:8000/products/${id}`);

Or if you want to use /products/${id} this pattern then you can add proxy into package.json like this.

//package.json
...
"proxy": "http://127.0.0.1:8000", // add this as proxy
...

After adding this you can use URLs patterns without using the hostname http://127.0.0.1:8000. in all over the app.

e.g:

const { data } = await axios.get(`/products/${id}`);

This should work now. If still, it gives an error 404 then might be an issue with your URLs patterns in the urls.py in the Django URLs.

Related