(props: SessionProviderProps)
| 363 | * |
| 364 | */ |
| 365 | export function SessionProvider(props: SessionProviderProps) { |
| 366 | if (!SessionContext) { |
| 367 | throw new Error('React Context is unavailable in Server Components'); |
| 368 | } |
| 369 | |
| 370 | const { children, basePath, refetchInterval, refetchWhenOffline } = props; |
| 371 | |
| 372 | if (basePath) __LINEN_AUTH.basePath = basePath; |
| 373 | |
| 374 | /** |
| 375 | * If session was `null`, there was an attempt to fetch it, |
| 376 | * but it failed, but we still treat it as a valid initial value. |
| 377 | */ |
| 378 | const hasInitialSession = props.session !== undefined; |
| 379 | |
| 380 | /** If session was passed, initialize as already synced */ |
| 381 | __LINEN_AUTH._lastSync = hasInitialSession ? now() : 0; |
| 382 | |
| 383 | const [session, setSession] = React.useState(() => { |
| 384 | if (hasInitialSession) __LINEN_AUTH._session = props.session; |
| 385 | return props.session; |
| 386 | }); |
| 387 | |
| 388 | /** If session was passed, initialize as not loading */ |
| 389 | const [loading, setLoading] = React.useState(!hasInitialSession); |
| 390 | |
| 391 | React.useEffect(() => { |
| 392 | __LINEN_AUTH._getSession = async ({ event }: any = {}) => { |
| 393 | try { |
| 394 | const storageEvent = event === 'storage'; |
| 395 | // We should always update if we don't have a client session yet |
| 396 | // or if there are events from other tabs/windows |
| 397 | if (storageEvent || __LINEN_AUTH._session === undefined) { |
| 398 | __LINEN_AUTH._lastSync = now(); |
| 399 | __LINEN_AUTH._session = await getSession({ |
| 400 | broadcast: !storageEvent, |
| 401 | }); |
| 402 | setSession(__LINEN_AUTH._session); |
| 403 | return; |
| 404 | } |
| 405 | |
| 406 | if ( |
| 407 | // If there is no time defined for when a session should be considered |
| 408 | // stale, then it's okay to use the value we have until an event is |
| 409 | // triggered which updates it |
| 410 | !event || |
| 411 | // If the client doesn't have a session then we don't need to call |
| 412 | // the server to check if it does (if they have signed in via another |
| 413 | // tab or window that will come through as a "storage" event |
| 414 | // event anyway) |
| 415 | __LINEN_AUTH._session === null || |
| 416 | // Bail out early if the client session is not stale yet |
| 417 | now() < __LINEN_AUTH._lastSync |
| 418 | ) { |
| 419 | return; |
| 420 | } |
| 421 | |
| 422 | // An event or session staleness occurred, update the client session. |
nothing calls this directly
no test coverage detected