React fetch file with params

The URLSearchParams interface is handy when building a request.

let searchParams = new URLSearchParams(window.location.search);

Then do whatever with the parameters and do the fetch, in this case a php-file returning json-data.

let a = "https://someserver.com/somefile.php";
if (!searchParams.entries().next().done) {  
   a += "?" + searchParams;        
}
       
fetch(a)            
.then( response => { return response.json() })            
.then( json => {  
   this.setState({
      myData:json
   });
});

Leave a comment