Search code examples
javascriptreact-routerreact-hooksreact-router-domurlsearchparams

How to parse the complete link in the url query string?


URL: https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321

code:

import { useLocation } from "react-router-dom";

function useQuery() {
  const {search} = useLocation();
  const query = new URLSearchParams(search);
  console.log('name: ', query.get('name'))
  console.log('url: ', query.get('url'))
  return query
}

Output:

name:  netflix 
url:  https://localhost?apikey=123 

As you can see, the code parameter is lost. I expect the value of url parameter should be https://localhost?apikey=123&code=321.

package version:

"react-router-dom": "5.2.0"

Solution

  • This happens because you haven't encoded the URI components. you can use encodeURIComponent and decodeURIComponent functions to solve your problem. Before push to the route encode the URL and after receiving you can decode it.

    Note: Please consider that decoding is not necessary because, new URLSearchParams(search).get('key') command will automatically decode the component.

    // In navigating component
    
    const history = useHistory();
    
    return (
        ...
        <button onClick={() => history.push(`/?name=netflix&url=${encodeURIComponent('https://localhost?apikey=123&code=321')}`)}>
            Go to link
        </button>
        ...
    )
    
    import { useLocation } from "react-router-dom";
    
    function useQuery() {
      const {search} = useLocation();
      const query = new URLSearchParams(search);
      console.log('name: ', query.get('name'))    // name: netflix 
      console.log('url: ', query.get('url'))      // url: https://localhost?apikey=123&code=321 
      return query;
    }