Search code examples
javascriptreactjsurlurlencode

useLocation hook have bugs when I reload page


I use useLocation to get data from url, first time it worked fine. But when I reload page, string search of location will contain encode string.

Is this what the useLocation hook does?

first load after reload

import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch, useHistory, useLocation } from 'react-router-dom';

function Home() {
  const history = useHistory();

  const handleSearch = () => {
    history.push('/search?q=test 123'); 
  };

  return (
    <div>
      <button onClick={handleSearch}>Search "test 123"</button>
    </div>
  );
}

function SearchResults() {
  const location = useLocation();
  console.log(location);
  const search = location.search;
  const queryParams = new URLSearchParams(search);
  const query = queryParams.get('q');

  return (
    <div>
      <h2>Search Results</h2>
      <p>Displaying search results for: {query}</p>
    </div>
  );
}

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/search?q=react test">Search</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/search" component={SearchResults} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

I want to know what's going on here, why is it like that.


Solution

  • This is completely normal behavior. Given URL path + search params "/search?q=test%20123" the URLSearchParams appears to correctly decodes the string. I've copy/pasted your code into a sandbox and the search component correctly displays "test 123" as you intended.

    Why is the search attribute of location different in the two cases?

    First Case

    enter image description here

    You didn't use the browser to request/load a page via the URL the first time, you used the internal routing that React-Router-DOM handles, and React-Router-DOM only updates the URL in the address bar and does not make any page request to any server.

    Second Case

    enter image description here

    For the second case, your browser encoded the space in the URL when you reloaded the page, the browser does this when it does make a request to the server for a document.