Skip to content

feat(react): refactor update session logic into a separate callback #12960

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 28 additions & 23 deletions packages/next-auth/src/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ export function SessionProvider(props: SessionProviderProps) {
}, [])

React.useEffect(() => {
const { refetchOnWindowFocus = true } = props
const refetchOnWindowFocus = props.refetchOnWindowFocus ?? true
// Listen for when the page is visible, if the user switches tabs
// and makes our tab visible again, re-fetch the session, but only if
// this feature is not disabled.
Expand Down Expand Up @@ -502,6 +502,31 @@ export function SessionProvider(props: SessionProviderProps) {
}
}, [refetchInterval, shouldRefetch])

const update = React.useCallback(
async (data: any) => {
if (loading) return
setLoading(true)
const newSession = await fetchData<Session>(
"session",
__NEXTAUTH,
logger,
typeof data === "undefined"
? undefined
: { body: { csrfToken: await getCsrfToken(), data } }
)
setLoading(false)
if (newSession) {
setSession(newSession)
broadcast().postMessage({
event: "session",
data: { trigger: "getSession" },
})
}
return newSession
},
[loading]
)

const value: any = React.useMemo(
() => ({
data: session,
Expand All @@ -510,29 +535,9 @@ export function SessionProvider(props: SessionProviderProps) {
: session
? "authenticated"
: "unauthenticated",
async update(data: any) {
if (loading) return
setLoading(true)
const newSession = await fetchData<Session>(
"session",
__NEXTAUTH,
logger,
typeof data === "undefined"
? undefined
: { body: { csrfToken: await getCsrfToken(), data } }
)
setLoading(false)
if (newSession) {
setSession(newSession)
broadcast().postMessage({
event: "session",
data: { trigger: "getSession" },
})
}
return newSession
},
update,
}),
[session, loading]
[session, loading, update]
)

return (
Expand Down