There is a state userIsAuthenticated in my parent App component which is false by default but becomes true with the setUserIsAuthenticated() function when the user is logged in.
Now, in another component, I would like to display some user's data such as the username. The user data is fetched from the backend API with Apollo:
Here is the component:
import React from 'react';
import { useQuery } from "@apollo/client";
import { ME } from "../../api/authentication/me";
import LogoutButton from "../authentication/authentication-required/logout-button";
const Nav = ({ userIsAuthenticated }) => {
const { data, loading, errors } = useQuery(ME);
if (loading) return "User is loading...";
if (errors) console.log(errors);
return (
<div className="Nav">
{/* internalState = { internalState } */}
<br />
{ JSON.stringify(data, null, 2) }
<br />
<LogoutButton/>
</div>
)
}
Here is my problem: When the user logs in, the query is performed again but the component is not refreshed. This only works if I go on another page (I'm using react-router-dom) or if I refresh the page.
I know that in React, a state must change in the component or in its children in order to be rendered again, so I tried using update states in it which change when the received props userIsAuthenticated changes.
Here is an example of what I tried:
const Nav = ({ userIsAuthenticated }) => {
const { data, loading, errors, refetch } = useQuery(ME);
const [internalState, setInternalState] = useState(userIsAuthenticated);
const [perviousValue, setPerviousValue] = useState();
if (userIsAuthenticated !== perviousValue){
const refetchMe = async() => {
await setTimeout(() => await refetch();
}
refetchMe();
setInternalState(userIsAuthenticated);
setPerviousValue(userIsAuthenticated);
}
console.log(internalState); // To check if the state is correctly updated
if (loading) return "User is loading...";
if (errors) console.log(errors);
return (
<div className="Nav">
{/* internalState = { internalState } */}
<br />
{ JSON.stringify(data, null, 2) }
<br />
<LogoutButton/>
</div>
)
But this doesn't solve the issue. The component is still not rerendered as long as I don't refresh the page or if I don't go to another page.
I also tried with the useEffect hook but I always end up in an infinite loop dispite only putting my userIsAuthenticated props in the dependency array.
Is there a way to rerender the component after refetching the query without having to refresh the page or moving to another one?