mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-01-10 20:48:54 +01:00
⌚ refactor: debounce setUserContext to avoid race condition
This commit is contained in:
parent
deb8a00e27
commit
45e4e70986
1 changed files with 28 additions and 23 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import {
|
||||
useRef,
|
||||
useMemo,
|
||||
useState,
|
||||
useEffect,
|
||||
|
|
@ -6,10 +7,10 @@ import {
|
|||
useContext,
|
||||
useCallback,
|
||||
createContext,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { debounce } from 'lodash';
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { setTokenHeader, SystemRoles } from 'librechat-data-provider';
|
||||
import type * as t from 'librechat-data-provider';
|
||||
import {
|
||||
|
|
@ -47,27 +48,31 @@ const AuthContextProvider = ({
|
|||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const setUserContext = useCallback(
|
||||
(userContext: TUserContext) => {
|
||||
const { token, isAuthenticated, user, redirect } = userContext;
|
||||
setUser(user);
|
||||
setToken(token);
|
||||
//@ts-ignore - ok for token to be undefined initially
|
||||
setTokenHeader(token);
|
||||
setIsAuthenticated(isAuthenticated);
|
||||
// Use a custom redirect if set
|
||||
const finalRedirect = logoutRedirectRef.current || redirect;
|
||||
// Clear the stored redirect
|
||||
logoutRedirectRef.current = undefined;
|
||||
if (finalRedirect == null) {
|
||||
return;
|
||||
}
|
||||
if (finalRedirect.startsWith('http://') || finalRedirect.startsWith('https://')) {
|
||||
window.location.href = finalRedirect;
|
||||
} else {
|
||||
navigate(finalRedirect, { replace: true });
|
||||
}
|
||||
},
|
||||
const setUserContext = useMemo(
|
||||
() =>
|
||||
debounce((userContext: TUserContext) => {
|
||||
const { token, isAuthenticated, user, redirect } = userContext;
|
||||
setUser(user);
|
||||
setToken(token);
|
||||
//@ts-ignore - ok for token to be undefined initially
|
||||
setTokenHeader(token);
|
||||
setIsAuthenticated(isAuthenticated);
|
||||
|
||||
// Use a custom redirect if set
|
||||
const finalRedirect = logoutRedirectRef.current || redirect;
|
||||
// Clear the stored redirect
|
||||
logoutRedirectRef.current = undefined;
|
||||
|
||||
if (finalRedirect == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (finalRedirect.startsWith('http://') || finalRedirect.startsWith('https://')) {
|
||||
window.location.href = finalRedirect;
|
||||
} else {
|
||||
navigate(finalRedirect, { replace: true });
|
||||
}
|
||||
}, 50),
|
||||
[navigate, setUser],
|
||||
);
|
||||
const doSetError = useTimeout({ callback: (error) => setError(error as string | undefined) });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue