Home > OS >  No routes matched location "/cart/2?qty= 1" react router dom v6
No routes matched location "/cart/2?qty= 1" react router dom v6

Time:03-21

i'am trying to organise my routes application using react-router-dom v6 so there is when I want to access the CartPage component by clicking on the button "Add To Cart" inside ProductPage component I reach an empty page without the expected information that I maked it on CartPage component there's my code :

the ProductPage code:

import React from "react";
import {Link, useParams, useNavigate} from "react-router-dom";
import Rating from "../components/Rating";
import {useSelector, useDispatch} from "react-redux";
import {useEffect, useState} from "react";
import {detailsProduct} from "../actions/productAction";
import LoadingBox from "../components/LoadingBox";
import ErrorBox from "../components/ErrorBox";

function ProductPage (props) {
    const dispatch = useDispatch();
    const { id } = useParams();
    useEffect(()=> {
     dispatch(detailsProduct(id));  

    }, [dispatch, id]);
    const [qty, setQty] = useState(1);
    const productDetails = useSelector((state) => state.productDetails);
    const {loading, error, product} = productDetails;
    console.log(product);
    
    const navigate = useNavigate(); 
    
    const addToCartHandler = () => {
        

        navigate(`/cart/${id}?qty= ${qty}`)
    }

            
    return (
            <div>
        {
            loading ?( <LoadingBox> </LoadingBox>) : error ?( <ErrorBox variant="danger" >{error}</ErrorBox>): (  <div>
        <Link to="/" >Back to result</Link>
           <div className="row top" >
             <div className="col-2" >
             <img className="large" src={product.images} alt={product.name} />
             </div>
             <div className="col-1" >
             <ul>
               <li>
                <h1>{product.name}</h1>
               </li>
               <li>
                <Rating rating={product.rating} numReviews={product.numReviews} ></Rating>
               </li>
               <li>
                Price: ${product.price}
               </li>
               <li>
                Description:
                <p>{product.description}</p>
               </li>
             </ul>
             </div>
             <div className="col-1" >
               <div className="card card-body" >
                    <ul>
                        
                        <li>
                          <div className="row">
                            <div>Price</div>
                            <div className="price">${product.price}</div>
                          </div>
                         </li>
                         <li>
                          <div className="row">
                            <div>Status</div>
                            <div>
                            {product.countInStock > 0 ? (<span className="success" >In stock</span>): (
                            <span className="danger">Unvailable</span>) }
                            </div>
                          </div>
                         </li>
                         {product.countInStock > 0 && (
                            <>
                            <li>
                              <div className="row" >
                               <div>Qty</div>
                               <div>
                                <select value={qty} onChange={e=> setQty(e.target.value)} >
                                {
                                  [...Array(product.countInStock).keys()].map(x=> 
                                  <option key={x   1} value={x   1} >{x   1} </option>
                                  )}
                                </select>
                               </div>
                              </div>
                            </li>
                              <li> <button onClick={addToCartHandler} className="primary block" >Add to Cart</button> </li> 
                            </>
                            
                            )}
                            </ul>
               </div>
             </div>
           </div>

        </div> )}
                </div>
        
    )

};
export default ProductPage;
CartPage code:
import React from "react";
import {useParams, useSearchParams} from "react-router-dom";

const CartPage = (props) => {
    const {id} = useParams();
    const [searchParams] = useSearchParams();
    const qty = searchParams('qty');
    console.log(qty)
    return (
        <div>
          <h1>Cart Page</h1>
          <p>Add to cart : ProductId : {id} Qty: {qty}</p>
        </div>
    )
};
export default CartPage;
App.js code:
import React from "react";
import HomePage from "./pages/HomePage"
import {BrowserRouter, Routes, Route} from "react-router-dom";
import ProductPage from "./pages/ProductPage";
import CartPage from "./pages/CartPage";

function App() {
  return (
    <BrowserRouter>
    <div className="grid-container">
      <header className="row" >
        <div>
          <a href="/" className="brand" >MyShop</a>
        </div>
        <div>
          <a href="/cart">Cart</a>
          <a href="/signin">Sign In </a>
        </div>
      </header>
      <main>
      
       <Routes>
       <Route path="/cart/:id?" element={<CartPage />} />
          <Route path="/" element={<HomePage />} />
          <Route path="/product/:id" element={<ProductPage />} /> 
        </Routes>
        
    <div>
       
      </div>
      </main>
      <footer className="row center" >
        All right reserved
      </footer>
    </div>
    </BrowserRouter>
  );
}

export default App;

CodePudding user response:

There is a space in qty= ${qty} that need to remove

  navigate(`/cart/${id}?qty= ${qty}`)

will be

navigate(`/cart/${id}?qty=${qty}`)

URL is "/cart/2?qty= 1" but should be "/cart/2?qty=1" comes because of space

CodePudding user response:

I think you are using useSearchParams wrong, You are directly trying to access the query params and you can't use searchparams that way.

Try using it like below:

const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("qty")
  • Related