This react component is triggered twice cause of the strict mode

50 Views Asked by At

I tried to create a variable outside and assigning the state to it, but it doesn't work. i really can't figure it out. i don't know what triggers the strict mode and when i assign the state to a variable it's worst. this is the code:

export const ProfilePage: React.FC = () => {
  const {user} = useAuth0();
  const [userData, setUserData] = useState<GetUserInfoResponse>();

  const {getAccessTokenSilently} = useAuth0();
  const client = useClient(UserService);

  useEffect(() => {
    let isMounted = true;

    const getMessage = async () => {
      const accessToken = await getAccessTokenSilently();

      const request = new GetUserInfoCommand({});
      const headers = new Headers();
      headers.set('Authorization', 'Bearer ' + accessToken);

      try {
        const resp: GetUserInfoResponse = await client.getUserInfo(request, {
          headers: headers,
          timeoutMs: 10000,
        });

        console.log(resp);

        setUserData(resp);
      } catch (err) {
        if (err instanceof ConnectError && err.code === Code.DeadlineExceeded) {
          console.log('Timeout');
        }
      }

      if (!isMounted) {
        return;
      }
    };

    getMessage();

    return () => {
      isMounted = false;
    };
  }, [getAccessTokenSilently]);
  if (!user) {
    return null;
  }
1

There are 1 best solutions below

1
ADITYA On

you're encountering issues related to state management and side effects with React hooks, particularly in the context of using Auth0 for user authentication and fetching user data. try this code:

export const ProfilePage: React.FC = () => {
  const { user, getAccessTokenSilently } = useAuth0();
  const [userData, setUserData] = useState<GetUserInfoResponse | null>(null); // Initialize with null

  const client = useClient(UserService);

  useEffect(() => {
    let isMounted = true;

    const fetchData = async () => {
      try {
        const accessToken = await getAccessTokenSilently();

        const request = new GetUserInfoCommand({});
        const headers = new Headers();
        headers.set('Authorization', 'Bearer ' + accessToken);

        const resp: GetUserInfoResponse = await client.getUserInfo(request, {
          headers: headers,
          timeoutMs: 10000,
        });

        console.log(resp);

        if (isMounted) {
          setUserData(resp);
        }
      } catch (err) {
        console.error('Error fetching user data:', err);
      }
    };

    fetchData();

    return () => {
      isMounted = false;
    };
  }, [getAccessTokenSilently, client]);

  if (!user) {
    return <div>Loading...</div>; // or any other handling for unauthenticated state
  }

  if (!userData) {
    return <div>Loading user data...</div>; // Display a loading message while fetching user data
  }

  // Render your component with user data
  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      {/* Render user data here */}
    </div>
  );
};