Ricardo Mayerhofer
Ricardo Mayerhofer

Reputation: 2309

Unable to get query string: pathname is filled but search is empty

I'm using react router + redux + redux saga. I access the location object passed as props to my component, where I try to get the query string part of the URL.

However, the search parameter of location is always empty. Nonetheless the pathname is filled as follows:

{pathname: "/view/energy?latitude=34.06012&longitude=-118.26997&zoom=11", search: "", hash: "", key: "wsbbq0"}

Any help or debug tip is appreciated. Thanks!

Libs versions:

"react-redux": "^7.2.0",
"react-router-dom": "^5.1.2",
"redux-saga": "^1.1.3"

Index

ReactDOM.render(
   <Provider store={store}>
      <Router>
         <Route path="/" component={App} />
         <Route path="/view/:viewId" component={App} />
      </Router>
   </Provider>,
   document.getElementById('root'));

Upvotes: 4

Views: 2586

Answers (1)

Drew Reese
Drew Reese

Reputation: 202658

According to location it should have split your url into

{
  pathname: "/view/energy",
  search: "?latitude=34.06012&longitude=-118.26997&zoom=11",
  hash: "",
  key: "wsbbq0"
}

but that didn't occur.

The reason it didn't occur is because you are using the to object form and have specified the queryString as part of the pathname property, and then explicitly specified an empty string for the search property. Never the less, consider the following way to navigate to a pathname+search:

  •  <Link to="/view/energy?latitude=34.06012&longitude=-118.26997&zoom=11">
       View Energy
     </Link>
    
    Correctly parses the target path string into its constituent parts:
    {
      "pathname": "/view/energy",
      "search": "?latitude=34.06012&longitude=-118.26997&zoom=11",
      "hash": "",
      "key": "qje5v8"
    }
    
  •  <Link
       to={{
         pathname:
           "/view/energy?latitude=34.06012&longitude=-118.26997&zoom=11"
       }}
     >
       View Energy
     </Link>
    
    Failed to separate the queryString:
    {
      "pathname": "/view/energy?latitude=34.06012&longitude=-118.26997&zoom=11",
      "search": "", // <-- empty string
      "hash": "",
      "key": "f6eqol"
    }
    
  •  <Link
       to={{
         pathname: "/view/energy",
         search: "?latitude=34.06012&longitude=-118.26997&zoom=11"
       }}
     >
       View Energy
     </Link>
    
    Correctly maintains the target path object's constituent parts:
    {
      "pathname": "/view/energy",
      "search": "?latitude=34.06012&longitude=-118.26997&zoom=11",
      "hash": "",
      "key": "9qlzx8"
    }
    

Edit unable-to-get-query-string-pathname-is-filled-but-search-is-empty

Upvotes: 2

Related Questions