fix: initialize auth in RQ client

This commit is contained in:
Ali BARIN
2024-03-04 10:48:55 +00:00
parent 73bd90c555
commit 930843d065
4 changed files with 21 additions and 8 deletions

View File

@@ -1,11 +1,14 @@
import { ApolloProvider as BaseApolloProvider } from '@apollo/client';
import * as React from 'react';
import { mutateAndGetClient } from 'graphql/client';
import useAuthentication from 'hooks/useAuthentication';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
const ApolloProvider = (props) => {
const enqueueSnackbar = useEnqueueSnackbar();
const authentication = useAuthentication();
const onError = React.useCallback(
(message) => {
enqueueSnackbar(message, {
@@ -17,12 +20,15 @@ const ApolloProvider = (props) => {
},
[enqueueSnackbar],
);
const client = React.useMemo(() => {
return mutateAndGetClient({
onError,
token: authentication.token,
});
}, [onError, authentication]);
return <BaseApolloProvider client={client} {...props} />;
};
export default ApolloProvider;

View File

@@ -33,11 +33,11 @@ export default function AutomatischQueryClientProvider({ children }) {
if (token) {
api.defaults.headers.Authorization = token;
initialize();
} else {
delete api.defaults.headers.Authorization;
}
initialize();
},
[initialize, token],
);

View File

@@ -1,12 +1,18 @@
import * as React from 'react';
import { getItem, setItem } from 'helpers/storage';
export const AuthenticationContext = React.createContext({
token: null,
updateToken: () => void 0,
isAuthenticated: false,
initialize: () => void 0,
});
export const AuthenticationProvider = (props) => {
const { children } = props;
const [isInitialized, setInitialized] = React.useState(false);
const [token, setToken] = React.useState(() => getItem('token'));
const value = React.useMemo(() => {
return {
token,
@@ -14,8 +20,13 @@ export const AuthenticationProvider = (props) => {
setToken(newToken);
setItem('token', newToken);
},
isAuthenticated: Boolean(token) && isInitialized,
initialize: () => {
setInitialized(true);
},
};
}, [token]);
}, [token, isInitialized]);
return (
<AuthenticationContext.Provider value={value}>
{children}

View File

@@ -4,9 +4,5 @@ import { AuthenticationContext } from 'contexts/Authentication';
export default function useAuthentication() {
const authenticationContext = React.useContext(AuthenticationContext);
return {
token: authenticationContext.token,
updateToken: authenticationContext.updateToken,
isAuthenticated: Boolean(authenticationContext.token),
};
return authenticationContext;
}