1- import React , { useEffect , FC } from 'react'
2- import { useQuery } from 'react-apollo'
3- import { useRuntime , canUseDOM , Loading } from 'vtex.render-runtime'
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'
49
5- import getAuthenticatedUser from './graphql/getAuthenticatedUser.graphql '
10+ import { getSession } from './modules/session '
611
712const loginPath = '/login'
813
@@ -16,18 +21,35 @@ const getLocation = () =>
1621 pathName : window . location . pathname ,
1722 }
1823 : {
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
24+ url : ( global as any ) . __pathname__ ,
25+ pathName : ( global as any ) . __pathname__ ,
2126 }
2227
23- const useStoreGraphqlSession = ( ) => {
24- const shouldRunQuery = canUseDOM
28+ const useSessionResponse = ( ) => {
29+ const [ session , setSession ] = useState < SessionResponse > ( )
30+ const sessionPromise = getSession ( )
2531
26- const { data, loading, error } = useQuery ( getAuthenticatedUser , {
27- skip : ! shouldRunQuery ,
28- } )
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 ] )
2943
30- return { data, loading, error }
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+ )
3153}
3254
3355const useLoginRedirect = ( isLoggedIn : boolean | null , page : string ) => {
@@ -53,12 +75,10 @@ interface Props {
5375}
5476
5577const ProfileChallenge : FC < Props > = ( { children, page } ) => {
56- const storeGraphqlSession = useStoreGraphqlSession ( )
57-
58- const isLoggedIn =
59- storeGraphqlSession . loading === false
60- ? ! ! storeGraphqlSession . data ?. authenticatedUser ?. id
61- : null
78+ const session = useSessionResponse ( )
79+ const isLoggedIn = hasSession ( session )
80+ ? session . namespaces ?. profile ?. isAuthenticated ?. value === 'true'
81+ : null
6282
6383 useLoginRedirect ( isLoggedIn , page )
6484
0 commit comments