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.