javascripturlpathwindow.locationurlsearchparams

Reading the parameter values off the current URL on page load


I realize retrieving search params from the URL is a commonly asked Question but I am running into an issue with using URLSearchParams(window.location.search) because I believe it is searching for a ? and my url contains & as separators between values.

my url will look something like this

http://localhost:8080/monitor/patientName=Courtney+Patient&pageSize=50

My Goal is to pull out the searchParams in the url and add them to the state of my component on load. So I am reading the whole URL and splitting it at the / this is giving me an array that looks something like this:

const queryString = window.location.pathname.split("/")[2]
const queries = queryString.split("&")

where queries returns: 
["patientName=Courtney+Patient","pageSize=50"]

I am hoping to loop over my default state and if queries contains lets say patientName the value will be replaced with the value held in the URL.

But I am not sure how to access the keys with varying lengths and compare them to the defaultStates keys. I am wondering if theres a way to get the keys inside the URL without using .split("") over and over?


Solution

  • I think a valid query string requires a ? before the first parameter name.

    I think it might be best to avoid using + as it might be a bit confusing.

    So, I think your URL should look something like this: http://localhost:8080/monitor/?patientName=Courtney&pageSize=50

    Now window.location.search will give you patientName=Courtney&pageSize=50

    In order to get the values of the patientName and pageSize parameters you can use this code:

    const params = new URLSearchParams(window.location.search);
    
    for (const [key, value] of params){
      console.log(key, ': ', value);
    }
    

    This is demonstrated in the snippet below where I have substituted window.location.search for 'patientName=Courtney&pageSize=50' because the window object is not available to me in the context of the snippet:

    const params = new URLSearchParams('patientName=Courtney&pageSize=50');
    
    for (const [key, value] of params){
      console.log(key, ': ', value);
    }

    I hope this helps.