'After jwt verification the state change is not presisting

So on the front end I'm using this function to have the user Log In if they have a This Function only works at the time of log in and after if the users just navigates to a different page on the site then it resets the userData state's values to undefined, The api link "http://localhost:5000/users/isTokenValid" returns either true or false

const [adminData, setAdminData] = useState({
        token: undefined,
        user: undefined,
    });
    const [authData, setAuthData] = useState(undefined);

    const [userData, setUserData] = useState({
        token: undefined,
        user: undefined,
    });

    useEffect(() => {
        const checkLoggedIn = async () => {
            let token = localStorage.getItem('auth-token');

            if (token === null) {
                localStorage.setItem('auth-token', '');
                token = '';
            }

            const tokenRes = await axios.post(
                'http://localhost:5000/users/isTokenValid',
                null,
                { headers: { 'x-auth-token': token } },
            );
            if (tokenRes.data) {
                const userRes = axios.get('http://localhost:5000/users/', {
                    headers: { 'x-auth-token': token },
                });
                setUserData({
                    token,
                    user: userRes.data,
                });
            }
        };

        checkLoggedIn();
    }, []);
return (
        <UserContext.Provider value={{ userData, setUserData }}>
            <AdminContext.Provider value={{ adminData, setAdminData }}>
                <AuthContext.Provider value={{ authData, setAuthData }}>
                    <Routes />
                </AuthContext.Provider>
            </AdminContext.Provider>
        </UserContext.Provider>
    );


Solution 1:[1]

I didn't add await.

        if (tokenRes.data) {
            const userRes = await axios.get('http://localhost:5000/users/', {
                headers: { 'x-auth-token': token },
            });
            setUserData({
                token,
                user: userRes.data,
            });
        }

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 vinzee