From c2da65c0ac8e7b535f74885114d0880b01de5b8f Mon Sep 17 00:00:00 2001 From: Nicolas Date: Mon, 17 May 2021 14:44:18 +0200 Subject: [PATCH 1/2] pass token directly to updateState --- src/KeycloakProvider.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/KeycloakProvider.tsx b/src/KeycloakProvider.tsx index 41bc651..bc7092a 100644 --- a/src/KeycloakProvider.tsx +++ b/src/KeycloakProvider.tsx @@ -50,7 +50,7 @@ export const KeycloakProvider: FC = (props) => { const updateState = useCallback( (callbackValue: any) => { - const tokens = callbackValue?.tokens ?? null; + const tokens = callbackValue ?? null; if (!!tokens) { saveTokens(tokens); if ( @@ -119,7 +119,10 @@ export const KeycloakProvider: FC = (props) => { }, [hydrated]); useEffect(() => { - handleTokenExchange({ response, discovery, config }).then(updateState); + handleTokenExchange({ response, discovery, config }) + .then((res) => { + if (res !== null) updateState(res.tokens); + }); }, [response]); return ( From 51ef2de8bc807bccba1faff64a968a152bc68f0c Mon Sep 17 00:00:00 2001 From: Nicolas Date: Mon, 17 May 2021 14:45:22 +0200 Subject: [PATCH 2/2] use ref to store callback instance --- src/KeycloakProvider.tsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/KeycloakProvider.tsx b/src/KeycloakProvider.tsx index bc7092a..9f6074f 100644 --- a/src/KeycloakProvider.tsx +++ b/src/KeycloakProvider.tsx @@ -1,4 +1,4 @@ -import React, { FC, useCallback, useEffect, useState } from 'react'; +import React, { FC, useCallback, useEffect, useRef, useState } from 'react'; import * as AuthSession from 'expo-auth-session'; import { TokenResponse, @@ -60,7 +60,7 @@ export const KeycloakProvider: FC = (props) => { clearTimeout(refreshHandle); setRefreshHandle( setTimeout( - handleTokenRefresh, + () => refreshCallBackRef.current(), ((tokens as TokenResponse).expiresIn! - (props.refreshTimeBuffer ?? REFRESH_TIME_BUFFER)) * 1000, @@ -113,9 +113,15 @@ export const KeycloakProvider: FC = (props) => { }, [discovery, savedTokens], ); + + const refreshCallBackRef = useRef(handleTokenRefresh); useEffect(() => { - if (hydrated) handleTokenRefresh(); + refreshCallBackRef.current = handleTokenRefresh; + }, [savedTokens]) + + useEffect(() => { + if (hydrated) refreshCallBackRef.current(); }, [hydrated]); useEffect(() => {