Search code examples
javascriptreactjsreact-reduxreact-props

Split out props.location.search value


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

query

As you can see quantity returns null, when I need the value selected

enter image description here


Solution

  • 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.

    1. Your query string is invalid– a ? 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
    2. If you follow the standard here, you can then split it two ways: by = and then by & to get the different parameters. However, there is an easier way.
    3. Using the new-ish URLSearchParams API, you can parse your parameters in a predictable 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