feat: introduce authentication context

This commit is contained in:
Ali BARIN
2022-03-08 19:50:51 +01:00
committed by Ömer Faruk Aydın
parent 030d886cf7
commit 5d1c4b81e7
8 changed files with 103 additions and 26 deletions

View File

@@ -1,7 +1,9 @@
import * as React from 'react';
import { ApolloProvider as BaseApolloProvider } from '@apollo/client';
import { useSnackbar } from 'notistack';
import client, { setLink } from 'graphql/client';
import useAuthentication from 'hooks/useAuthentication';
type ApolloProviderProps = {
children: React.ReactNode;
@@ -9,14 +11,15 @@ type ApolloProviderProps = {
const ApolloProvider = (props: ApolloProviderProps): React.ReactElement => {
const { enqueueSnackbar } = useSnackbar();
const authentication = useAuthentication();
const onError = React.useCallback((message) => {
enqueueSnackbar(message, { variant: 'error' });
}, [enqueueSnackbar]);
React.useEffect(() => {
setLink({ onError })
}, [onError]);
setLink({ onError, token: authentication.token })
}, [onError, authentication]);
return (
<BaseApolloProvider client={client} {...props} />

View File

@@ -6,6 +6,7 @@ import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton';
import useAuthentication from 'hooks/useAuthentication';
import * as URLS from 'config/urls';
import { setItem } from 'helpers/storage';
import { LOGIN } from 'graphql/mutations/login';
@@ -38,6 +39,7 @@ function renderFields(props: { loading: boolean }) {
required
fullWidth
margin="dense"
autoComplete="current-password"
/>
<LoadingButton
@@ -57,8 +59,15 @@ function renderFields(props: { loading: boolean }) {
function LoginForm() {
const navigate = useNavigate();
const authentication = useAuthentication();
const [login, { loading }] = useMutation(LOGIN);
React.useEffect(() => {
if (authentication.isAuthenticated) {
navigate(URLS.DASHBOARD);
}
}, [authentication.isAuthenticated]);
const handleSubmit = async (values: any) => {
const { data } = await login({
variables: {
@@ -68,9 +77,7 @@ function LoginForm() {
const { token } = data.login;
setItem('token', token);
navigate(URLS.FLOWS);
authentication.updateToken(token);
};
const render = React.useMemo(() => renderFields({ loading }), [loading]);