|
1 | 1 | 'use client'; |
2 | | -import React from 'react'; |
| 2 | +import React, { useEffect, useState } from 'react'; |
3 | 3 | import { SuperTokensWrapper } from 'supertokens-auth-react'; |
4 | 4 | import SuperTokensReact from 'supertokens-auth-react'; |
5 | 5 | import { AuthRecipeComponentsOverrideContextProvider } from 'supertokens-auth-react/ui'; |
6 | 6 | import { frontendConfig, setRouter } from '@/app/config/frontend'; |
7 | 7 | import { usePathname, useRouter } from 'next/navigation'; |
8 | 8 | import { useIsAdminRegisteredQuery } from '@/redux/services/users/authApi'; |
9 | 9 |
|
10 | | -if (typeof window !== 'undefined') { |
11 | | - // we only want to call this init function on the frontend, so we check typeof window !== 'undefined' |
12 | | - SuperTokensReact.init(frontendConfig()); |
13 | | -} |
| 10 | +let isInitialized = false; |
14 | 11 |
|
15 | 12 | export const SuperTokensProvider: React.FC<React.PropsWithChildren<{}>> = ({ |
16 | 13 | children, |
17 | 14 | }) => { |
18 | | - setRouter(useRouter(), usePathname() || window.location.pathname); |
| 15 | + const [isReady, setIsReady] = useState(isInitialized); |
| 16 | + const router = useRouter(); |
| 17 | + const pathname = usePathname(); |
| 18 | + |
| 19 | + useEffect(() => { |
| 20 | + const initializeSuperTokens = async () => { |
| 21 | + if (!isInitialized) { |
| 22 | + try { |
| 23 | + const config = await frontendConfig(); |
| 24 | + SuperTokensReact.init(config); |
| 25 | + isInitialized = true; |
| 26 | + setIsReady(true); |
| 27 | + } catch (error) { |
| 28 | + console.error('Failed to initialize SuperTokens:', error); |
| 29 | + setIsReady(true); |
| 30 | + } |
| 31 | + } else { |
| 32 | + setIsReady(true); |
| 33 | + } |
| 34 | + }; |
| 35 | + |
| 36 | + initializeSuperTokens(); |
| 37 | + }, []); |
| 38 | + |
| 39 | + useEffect(() => { |
| 40 | + setRouter(router, pathname || window.location.pathname); |
| 41 | + }, [router, pathname]); |
| 42 | + |
19 | 43 | const { data: isAdminRegistered } = useIsAdminRegisteredQuery(); |
20 | 44 |
|
| 45 | + if (!isReady) { |
| 46 | + return <div>Loading...</div>; |
| 47 | + } |
| 48 | + |
21 | 49 | return ( |
22 | 50 | <SuperTokensWrapper> |
23 | 51 | <AuthRecipeComponentsOverrideContextProvider |
|
0 commit comments