Warm tip: This article is reproduced from serverfault.com, please click

currentUser is undefined is displayed undefined

发布于 2020-11-27 22:37:11

I use react with redux and I have this problem that results in an infinite loop between login and profile. And when I remove the condition if(!cuurentUser) in profile for debugging it says that curentUser is undefined.

then please help me.

Thank you in advance.

import React from "react";
import { Redirect } from 'react-router-dom';
import { useSelector } from "react-redux";

const Profile = () => {
  const { currentUser }= useSelector((state) => state.auth);

 if (!currentUser) {
    return <Redirect to="/login" />;
  }

  return (
    <div className="container">
      <header className="jumbotron">
        <h3>
          <strong>{currentUser.username}</strong> Profile
        </h3>
      </header>
      <p>
        <strong>Token:</strong> {currentUser.accessToken.substring(0, 20)} ...{" "}
        {currentUser.accessToken.substr(currentUser.accessToken.length - 20)}
      </p>
      <p>
        <strong>Id:</strong> {currentUser.id}
      </p>
      <p>
        <strong>Email:</strong> {currentUser.email}
      </p>
      <strong>Authorities:</strong>
      <ul>
        {currentUser.roles &&
          currentUser.roles.map((role, index) => <li key={index}>{role}</li>)}
      </ul>
    </div>
  );
};

export default Profile;
Questioner
Sidou Didous
Viewed
0
Greg Konush 2020-11-28 06:54:55

The component that redirects to your Profile component has a logic of redirecting when the user logged in, most likely you are doing it with some useEffect hook. Also, that redirecting component needs to populate your Redux store correctly so then when you redirect to Profile component your currentUser is available in the store otherwise it will always render the Redirect