Click here to Skip to main content
15,349,320 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
> I have already performed most of the methods provided in the previous
> related queries and they didn't worked so please don't mark it as
> duplicate.

Inside the authentication context API to check whether an user is already logged in (by checking for cookie) I wrote a function which sends a get request to backend and an user JSON is returned if the JWT inside the cookie is valid and appropriate. If the user is valid then the `user` of `INITIAL_STATE` is set to the logged in user JSON otherwise it is set to `null`.
Context API code:

    const getUser = async () => {
        try {
            const response = await axios.get('users/', { withCredentials: true });
            if (response.status !== 200)
                return null;
            return response.data;
        } catch (error) {
            return null;
        }
    }
    
    const INITIAL_STATE = {
        user: getUser(),
        isFetching: false,
        error: false
    };
    
    export const AuthContext = createContext(INITIAL_STATE);

Now the problem here is that the `user` inside the `INITIAL_STATE` is getting set as the promise JSON.
[`user` inside `INITIAL_STATE` after request is processed][1]


  [1]: https://i.stack.imgur.com/FWiUf.png

I want to retrieve the Promise Object from the Promise JSON how can I do so?

Also if there is some better way of checking an already logged in user without reading the cookie on client side then please feel free to share...


What I have tried:

I have tried returning the response data instead of returning the promise.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900