0

React-router-dom Link doesn't work when I click on it, but when I refresh the page, the required page appears. Also, after reloading the page, the token and the user are not saved.

For example, when clicking on the login link, nothing happens. The login form only appears after the page is reloaded. After pressing the login button, the server returns the token, but there is no transition to the event page. After reloading the page, the event page appears, but the token is lost

App.js looks like this

function App() {
  const [user, setUser] = React.useState(null);
  const [token, setToken] = React.useState(null);
  const [error, setError] = React.useState('');

  async function login(user = null) {
    EventDataService.login(user)
    .then(response => {
      setToken(response.data.token);
      setUser(user.username);
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', user.username);
      setError('');
    })
    .catch(e => {
      setError(e.toString());
    });
  }

  async function logout() {
    setToken('');
    setUser('');
    localStorage.setItem('token', '');
    localStorage.setItem('user', '');
  }

  async function signup(user = null) {
    setUser(user);
    EventDataService.signup(user)
    .then(response => {
      setToken(response.data.token);
      setUser(user.username);
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', user);
    })
    .catch( e => {
      console.log(e);
      setError(e.toString());
    })
  }


  return (
    <div className="App">
      <header className="App-header">
      <ul className="nav justify-content-center">
        {
          user ? (
            <li className="nav-item">
              <Link className="nav-link text-light" onClick={logout}>Logout ({user})</Link>
            </li>
          ):(
            <>
              <li className="nav-item">
                <Link className="nav-link text-light active" aria-current="page" to={"/login"}>Login</Link>
              </li>
              <li className="nav-item">
                <Link className="nav-link text-light" to={"/signup"}>Sign Up</Link>
              </li>
            </>
          )}
      </ul>
        <h1
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Welcome { user ? user: '' }!
        </h1>
      </header>
      <div className='container'>

        <Switch>
          <Route exact path={["/", "/events"]} render={(props) =>
          // <EventList {...props} token={token} />
          <EventsList {...props} token={token} />
          }>
          </Route>
          <Route path="/login" render={(props)=>
          <Login {...props} login={login} />
          }>
          </Route>
          {/* <Route path="/login" render={(props)=>
          <LoginForm {...props} login={login} />
          }>
          </Route> */}
          <Route path="/signup" render={(props)=>
          <Signup {...props} signup={signup} />
          }>
          </Route>
        </Switch>
      </div>
    </div>
  );
}

React-router-dom version 5.2.0 installed.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    Are you wrapping everything with `BrowserRouter` anywhere? Since I can't see it in your `App` I suppose it's in your `index.js` maybe? If not, that may be the problem. – ivanatias Jul 28 '22 at 20:26
  • Yes, BrowserRouter added to index.js. – ilsurealism Jul 28 '22 at 20:48
  • 1
    What version of `react` are you using? If using React 18 does this help answer your question? https://stackoverflow.com/a/71833424/8690857 – Drew Reese Jul 30 '22 at 07:03
  • 1
    @DrewReese thanks! Yes, I'm using React 18.1.0 and your answer helped me. I just made the React.StrictMode component a child of the BrowserRouter component and everything started working! – ilsurealism Jul 30 '22 at 16:38
  • 1
    Great! Thanks for confirming that react version for me. IMHO the best option would be to update to at least v5.3.3 for the `StrictMode` fix, but the option you selected was the next best option prior to v5.3.3 going live. Cheers and good luck! – Drew Reese Jul 31 '22 at 02:16

1 Answers1

0

I've already had this problem using older versions of the React Router Instead, using the React Router V6 seemed to be the solution for me.

They did a good documentation about it here https://reactrouter.com/docs/en/v6/getting-started/tutorial

I hope it helped, good coding !