Apollo query too fast/localstorage too slow

Using apollo boost, and using the localstorage cacheLocation, on first login, my first query/queries do not have the token yet. Apolloclient reads from localstorage and apparently, when the queries are executed, the token is not written to localstorage:

const client = new ApolloClient({
    uri: '...',
    request: (operation) => {
        const token = getToken()
        if (null !== token)
            operation.setContext({
                headers: {
                    Authorization: `Bearer ${token}`
                }
            })

    }
})

I have a helper function for fetching the token getToken():

export const getToken = () => {
    const auth0spajs = localStorage.getItem("@@auth0spajs@@::...::openid profile email")
    return auth0spajs ? JSON.parse(auth0spajs).body.access_token : null
}

Using a query:

const Sessions = () => {
    const {loading, error, data} = useQuery(ALL_SESSIONS)
    if (loading) return <p>Loading...</p>;
    if (error) return <div><p>Error :( </p></div>;

    return data.Session.map((session) => (
        <p style={{fontSize: 'small'}} key={session.cuid}>{JSON.stringify(session)}</p>
    ));
}

How can I make the app/useQuery wait to load until the data is written to localstorage?

1 Like