I'm trying to split out the values from props.location.search in React/Redux. I've successfully obtained the mixOne split however I can't seem to return the value of quantity. Here's my code:
const mixOne = props.location.search
? String(props.location.search.split("mixOne=")[1])
: "None";
const quantity = props.location.search
? Number(props.location.search.split("=")[1])
: 1;
And here's the URL that gets generated:
const addToCartHandler = () => {
props.history.push(
`/Cart/${productId}?quantity=${quantity}?mixOne=${mixOne}`
);
};
As you can see quantity returns null, when I need the value selected
props.location.search.split("=")
on "?quantity=1?mixOne=Grape"
would return [ '?quantity', '1?mixOne', 'Grape' ]
since the next =
is not until after mixOne
.
There's a few different fixes here.
?
denotes the start of the query string. Separate parameters should be split up using &
ampersand characters. It should look like this: ?quantity=1&mixOne=Grape
=
and then by &
to get the different parameters. However, there is an easier way.// Use the constructor with your `props.location.search`
const queryParams = new URLSearchParams(props.location.search);
// Use the getters to grab a specific value
const quantity = queryParams.get("quantity");
// Ensure it's a number for safety
const quantityNum = Number(quantity);
// ... the rest of your code here