reactjsreact-router-domurlsearchparams

URLSearchParams not parsing query string


Using react-router-dom version 5.

Some component, rendered when matching a <Route />:

...

const { search } = useLocation();
const params = new URLSearchParams(search);

  useEffect(() => {
    console.log(search); // "?paramOne=1&paramTwo=2"
    console.log(params); // {}
  }, []);

...

Why does params not show { paramOne: "1", paramTwo: "2" }?


Solution

  • You are not using URLSearchParams as you should. You are getting URLSearchParams object and if you want to get it as a string, you should log params.toString()

    Check out these links:

    1. https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
    2. https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString