1- import React , { useState , useEffect , FC } from 'react'
2- import {
3- useRuntime ,
4- canUseDOM ,
5- Loading ,
6- SessionResponse ,
7- Session ,
8- } from 'vtex.render-runtime'
1+ import React , { useEffect , FC } from 'react'
2+ import { useQuery } from 'react-apollo'
3+ import { useRuntime , canUseDOM , Loading } from 'vtex.render-runtime'
94
10- import { getSession } from './modules/session '
5+ import getAuthenticatedUser from './graphql/getAuthenticatedUser.graphql '
116
127const loginPath = '/login'
138
@@ -21,35 +16,18 @@ const getLocation = () =>
2116 pathName : window . location . pathname ,
2217 }
2318 : {
24- url : ( global as any ) . __pathname__ ,
25- pathName : ( global as any ) . __pathname__ ,
19+ url : ( global as any ) . __pathname__ , // eslint-disable-line @typescript-eslint/no-explicit-any
20+ pathName : ( global as any ) . __pathname__ , // eslint-disable-line @typescript-eslint/no-explicit-any
2621 }
2722
28- const useSessionResponse = ( ) => {
29- const [ session , setSession ] = useState < SessionResponse > ( )
30- const sessionPromise = getSession ( )
23+ const useStoreGraphqlSession = ( ) => {
24+ const shouldRunQuery = canUseDOM
3125
32- useEffect ( ( ) => {
33- if ( ! sessionPromise ) {
34- return
35- }
36-
37- sessionPromise . then ( sessionResponse => {
38- const response = sessionResponse . response as SessionResponse
39-
40- setSession ( response )
41- } )
42- } , [ sessionPromise ] )
26+ const { data, loading, error } = useQuery ( getAuthenticatedUser , {
27+ skip : ! shouldRunQuery ,
28+ } )
4329
44- return session
45- }
46-
47- function hasSession ( session : SessionResponse | undefined ) : session is Session {
48- return (
49- session !== undefined &&
50- session . type !== 'Unauthorized' &&
51- session . type !== 'Forbidden'
52- )
30+ return { data, loading, error }
5331}
5432
5533const useLoginRedirect = ( isLoggedIn : boolean | null , page : string ) => {
@@ -75,10 +53,12 @@ interface Props {
7553}
7654
7755const ProfileChallenge : FC < Props > = ( { children, page } ) => {
78- const session = useSessionResponse ( )
79- const isLoggedIn = hasSession ( session )
80- ? session . namespaces ?. profile ?. isAuthenticated ?. value === 'true'
81- : null
56+ const storeGraphqlSession = useStoreGraphqlSession ( )
57+
58+ const isLoggedIn =
59+ storeGraphqlSession . loading === false
60+ ? ! ! storeGraphqlSession . data ?. authenticatedUser ?. id
61+ : null
8262
8363 useLoginRedirect ( isLoggedIn , page )
8464
0 commit comments