UNPKG

payload-authjs

Version:
96 lines (95 loc) 3.33 kB
"use client"; import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useCallback, useEffect, useState } from "react"; export const Context = /*#__PURE__*/ createContext({ status: "loading", session: null, refresh: ()=>new Promise((resolve)=>resolve(null)), refetch: ()=>new Promise((resolve)=>resolve(null)) }); /** * PayloadSessionProvider that provides the session to the context provider */ export const PayloadSessionProvider = ({ userCollectionSlug = "users", session = null, children })=>{ const [isLoading, setIsLoading] = useState(!session); const [localSession, setLocalSession] = useState(session); /** * Function to fetch the session */ const fetchSession = useCallback(async ({ signal } = {})=>{ /** * Fetch the session from the server * * @see https://payloadcms.com/docs/rest-api/overview#auth-operations */ const response = await fetch(`/api/${userCollectionSlug}/me`, { signal }); const result = await response.json(); // Set loading to false setIsLoading(false); // If the response is not ok or the user is not present, return null if (!response.ok || !result.user) { return null; } // Update the local session const localSession = { user: result.user, expires: new Date(result.exp * 1000).toISOString(), collection: result.collection, strategy: result.user._strategy ?? result.strategy }; setLocalSession(localSession); // Return the session return localSession; }, [ userCollectionSlug ]); /** * On mount, fetch the session */ useEffect(()=>{ const abortController = new AbortController(); void fetchSession({ signal: abortController.signal }); // Abort the fetch on unmount return ()=>{ abortController.abort(); }; }, [ fetchSession ]); /** * Function to refresh the session */ const refresh = async ()=>{ /** * Refresh the session on the server * * @see https://payloadcms.com/docs/rest-api/overview#auth-operations */ const response = await fetch(`/api/${userCollectionSlug}/refresh-token`, { method: "POST" }); const result = await response.json(); // If the response is not ok or the user is not present, return null if (!response.ok || !result.user) { return null; } // Update the local session const localSession = { user: result.user, expires: new Date(result.exp * 1000).toISOString(), collection: result.user.collection ?? userCollectionSlug, strategy: result.user._strategy ?? result.strategy }; setLocalSession(localSession); // Return the session return localSession; }; return /*#__PURE__*/ _jsx(Context, { value: { status: isLoading ? "loading" : localSession ? "authenticated" : "unauthenticated", session: localSession, refresh, refetch: fetchSession }, children: children }); }; //# sourceMappingURL=PayloadSessionProvider.js.map