0

I am using Protected Route for my dashboard and I only want people who signed in would be able to see the dashboard. So, in my Login component, I am fetching the data and this is the place where I check if the email and password of the user is right. So what I want to do is send a boolean variable to parent element which is index.js and according to the value I want to show the dashboard to the user. So here is my index.js:

const hist = createBrowserHistory();
console.log(hist)
ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route path="/" component={Login} exact />
      <ProtectedRoute path="/admin" component={(props) => <AdminLayout {...props} />} isAuth={true}/>
      <Route path="" component={() => "404 NOT FOUND"} />
    </Switch>
  </Router>,
  document.getElementById("root")
);

So instead of the true inside, isAuth={true}, I want to send a variable to check. Also my Login component:

const Login = ({ submitForm }) => {
  const [isSubmitted, setIsSubmitted] = useState(false);

  function submitForm() {
    setIsSubmitted(true);
  }
  const { handleChange, values, handleSubmit, errors } = useForm(
    submitForm,
    validate
  );

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [login, setLogin] = useState(false);

  const fetchLogin = async (email, password) => {
    try {
      setLoading(true);
      const res = await Axios({
        data: {
          user_email: email,
          user_password: password,
        },
      });
      if (res.status === 200) {
        setLogin(true);
        localStorage.setItem("user-info", JSON.stringify(res));
        
      }
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  function loginButton() {
    fetchLogin(values.email, values.password);
  }
  return (
    <form>
      
    </form>
  );
};

export default Login;

So thanks for your helps...

1 Answers1

2

There are different ways.

  1. You can read retrieve user-info from localStroage in your ProtectedRoute. In this case Login would not need to do anything more than localStorage.setItem("user-info", JSON.stringify(res))
  2. You can propagate the login-state up to the parent component using a callback function. See this question for an example.
  3. If you want to access the login state also from other components you could consider to use a React Context. Here is an example.
hendra
  • 2,531
  • 5
  • 22
  • 34