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 ;)

2

There are 2 best solutions below

1
mahan On BEST ANSWER

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

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

So I found an answer to the question I hope; I just changed this:

  const qty = queryParams ? Number(queryParams.get('qty').split('=')[1]) : 1;

to:

  const qty = queryParams ? Number(queryParams.get('qty')) : 1;

I hope this really fixed it for now, I sat on it for 2 hours... if anyone see's another problem in my code, an update, or something would love an opinion, but for now ReduxDevTools shows that quantity is updated everyclick on addToCart :)