'Loading a next-auth protected page shows the wrong message while and before loading

Consider a sinple next.js page like this

const Index: NextPage = () => {

    const {data: session} = useSession();
    const [data, setData] = useState(null);
    const [isLoading, setLoading] = useState(false);

    useEffect(() => {
            setLoading(true)
            fetch('/api/myEndpoint')
                .then((res) => res.json())
                .then((data) => {
                    setData(data);
                    setLoading(false);
                });
    }, []);

    if(isLoading) {
        return <Spinner/>;
    }

    if(session) {
        return <p>here is my protected content</p>
    } else {
        return <p>you cant see this page</p>
    }
}

When I am not logged in I see "you cant see this page", then the spinner, then again "you cant see this page". And that's fine.

But when I am logged in, I see "you cant see this page", then the spinner, and then the protected content.

Same thing even if I try

if(session && data) {

How can I get rid completly of the "you cant see this page" until the page is completly loaded?



Solution 1:[1]

Try : if(session && !isLoading) or if(session && isLoading===false)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DevGuy