javascriptreactjsreduxreact-hooksjavascript-framework

CartAddItem Wont add the URLSearchParams for Redux. Cant get location.search for Quantity props for my Cart - Shop Website


Following an old MERN Shop Brad Traversy course, and I'm trying to use URLSearchParams because of the location.

Search in the course isn't updated and gives endless bugs.

Practically, I just want to get the localhost:3000/id/?qty=1 <<< this (with no * of course.)

The "1" as a number to add to the cart; else I want it to be 1 as default.

The Code used in the courses is this (which had lots of bugs included) :

  const qty = location.search ? Number(location.search.split('=')[1]) : 1

Mine is this;

  const queryParams = new URLSearchParams(window.location.search);
  const qty = queryParams ? Number(queryParams.get('qty').split('=')[1]) : 1;

I saw the code isn't updated, so I tried to use URLSearchParams, of course would love opinions for another way to just catch the 1 from localhost:3000/id/?qty=1.

This is my CartScreen.js file:

import React, { useEffect } from 'react';
import { Link, useNavigate, useParams, useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import {
  Row,
  Col,
  ListGroup,
  Image,
  Form,
  Button,
  Card,
} from 'react-bootstrap';
import Message from '../components/Message';
import { addToCart } from '../actions/cartActions';

const CartScreen = () => {
  const navigate = useNavigate();
  const queryParams = new URLSearchParams(window.location.search);
  const qty = queryParams ? Number(queryParams.get('qty').split('=')[1]) : 1;

  const { id } = useParams();
  const productId = id;

  const dispatch = useDispatch();
  useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId, qty));
    }
  }, [dispatch, productId, qty]);

  return <div>CartScreen</div>;
};

export default CartScreen;

I tried also to use another ways, again would love an easy fix or any way that would just catch the querySearch.

I'm pretty sure I'm just tired, so in not seeing the easy fix.

Hope that you will :)

thanks in advance ;)


Solution

  • Use the useSearchParams hook since you use react-router-dom.

      const [searchParam, setSearchParams] = useSearchParams();
      const qty = Number(searchParam.get("qty")) ?? 1