Unable to match the url of add-to-cart handler with the path ('/cart/:id') in app.js

Viewed 492

using react-router-dom v 6. I'm short of the right words to word the question but the problem is that the url of addToCart handler is not finding the addToCart path in app.js. For example, when I click on a product that has id of 2, I get this error display in the console No routes matched location "/cart/2?qty=1" .The same applies to any other product selected.

function ProductScreen({}) {
    const [qty, setQty] = useState(1)

    const history = useNavigate()
    const match = useParams();
    const dispatch = useDispatch()
    const productDetails = useSelector(state => state.productDetails)
    const {error, loading, product} = productDetails

    useEffect(() => {
        dispatch(listProductDetails(match.id))
    }, [dispatch, match])

    const addToCartHandler = () =>{
        history(`/cart/${match.id}?qty=${qty}`)
    }
    return(
        <Button onClick={addToCartHandler} Add To Cart </Button>
    )
}

CartScreen

const CartScreen = () => {
    const { id } = useParams();
    const { search } = useLocation();
    const [searchParms] = useSearchParams();
  
    const productId = id;
    const qty = search ? Number(search.split("=")[1]) : 1;
  

    const dispatch = useDispatch()

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

    
    return (
      <div>
        <h1>Add to CART</h1>
      </div>
    );
  };
  
  export default CartScreen

App.js

function App() {
  return (
    <Router>
      <Routes>
        <Route path='/product/:id' element={<ProductScreen/>} />
        <Route path='/cart/:id' element={<CartScreen/>} />
        <Route path='/cart/' element={<CartScreen/>} />
      </Routes>
    </Router>
  );
}

Changing <Route path='/cart/:id' element={<CartScreen/>} /> to <Route path='/cart/:id?' element={<CartScreen/>} /> does not fix the issue. Note the difference in these two routes I tested is the ? in the path of the second route.

1 Answers

Given your code snippets copy/pasted into a codesandbox that is working, but the same exact code isn't working locally for you and you're still seeing an invariant error No routes matched location "/cart/2?qty=1" I suggest doing a full restart. The path "/cart/2" should certainly be matched.

Debugging/troubleshooting steps I typically take:

  • Killing any running code watchers/hot-reloaders, and fully clear browser caches, then restart development build (npm start)
  • Fully close out/reopen the browser, and then run your builds again
  • Try running them in an incognito window
  • Reboot the machine you're running the code on
Related