Samoila Andrei
Samoila Andrei

Reputation: 348

How do I fix redirecting for a react route?

I have a question regarding redirecting in React. here are my routes in my App.js file:

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about" component={About} />
          <Route path="/login">
            <Login onLoginSuccess={setUserSession} />
          </Route>
          <Route path="/register">
            <Register />
          </Route>
          <LoggedInRoute userData={getUserData()} path="/feed">
            <Feed />
          </LoggedInRoute>
        </Switch>

here is the LoggedInRoute component:

import React from 'react';

import { Redirect, Route } from "react-router-dom";

function LoggedInRoute(props) {
  return (
    <Route
      render={({ location }) =>
        props.userData.id ? (
          props.children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}

export default LoggedInRoute;

here is the login fetch:

  const onFinish = values => {
    fetch('/api/login',
      {
        method: 'POST',
        body: JSON.stringify(values)
      }
    ).then(response => response.json())
    .then(data => {
      if (data.success === 1) {
        if (location.state.from) {
          history.push(location.state.from.pathname);
        }
      }
    });
  };

my problem is that the redirect is not working after a successful login. If I try to access '/feed' when I am not logged in, in the first place I am redirected to the '/login', but after a successful login I am not redirected back to the initial route (/feed). I am not sure what I am missing. Thank you in advance, guys :)

Upvotes: 3

Views: 128

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

If I were you, I would go with this approach:

import { Redirect, Route, useLocation } from "react-router-dom";

function LoggedInRoute({ userData, children }) {
  const location = useLocation();
  const [redirect, setRedirect] = useEffect(false);

  useEffect(() => {
    if (!userData || !userData.id) {
      setRedirect(true);
    }
  }, [userData]);

  if (redirect) {
    return (
      <Redirect
        to={{
          pathname: "/login",
          state: { from: location }
        }}
      />
    );
  }

  return <Route component={<>{children}</>} />;
}

this way you won't get any stale data

Upvotes: 1

Related Questions