I have my django-rest-framework api running on port 80000. and my react project on port 3000. I have installed cors-headers in django and am making requests to api successfully, but there is one problem:
import axios from 'axios';
import { CART_ADD_ITEM } from '../constants/cartConstants';
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/products/${id}`);
dispatch({
type: CART_ADD_ITEM,
payload: {
product: data.id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.count_in_stock,
qty,
},
});
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
so axios should be making request to get product data from /api/products/${id}
this url and then update state in redux store which i'm calling in useEffect in CartPage component like this:
const CartPage = () => {
const productId = useParams()
const location = useLocation().search
const qty = location ? Number(location.split("=")[1]) : 1
const dispatch = useDispatch()
useEffect(() => {
if(productId) {
dispatch(addToCart(productId, qty))
}
}, [dispatch, productId, qty])
return (
<div>Cart</div>
)
}
export default CartPage
but there is an axios error which says GET http://127.0.0.1:8000/api/products/[object Object] 500 (Internal Server Error)
why am i getting this? and what is this object thing at the end after products/. anny feedback would be much appreciated. thanks
CodePudding user response:
I think you just miss one thing which needs to fix like this:
const { id } = useParams(); // you will get your product id like this
const productId = useParams() returns object that's why you get 500.