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

860 views Asked by At

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"
2

There are 2 answers

0
Nimna Perera On BEST ANSWER

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;
}
0
HOK On

Your code is correct, but your input URL is wrong.

If you use:

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

Your browser will read it as

Protocoll
https:
                Top Level Domain
                 .app
             Domain
              csb
      Sub-Domain
        n9hon
                         Params
                     ?name=netflix&url=https://localhost?apikey=123&code=321

What is OK, so far, but then stuff goes down the drain:

                        Param 1
                      name=netflix
                                          Param 2
                                   url=https://localhost?apikey=123
                                                                     Param 3
                                                                    code=321

If you want to get Param2 and Param 3 read as one Param, you need to get rid of the & (and to be clean also of the ? : = and /)

https://n9hon.csb.app?name=netflix&url=https%3A%2F%2Flocalhost%3Fapikey%3D123%26amp%3Bcode%3D321

In your code you can easily do this by encodeURI(uri) and revert it via decodeURI(enc)