feat: introduce snackbars for GQL errors

This commit is contained in:
Ali BARIN
2021-10-23 18:53:48 +02:00
parent 3e6220c39e
commit c7d757a337
4 changed files with 72 additions and 16 deletions

View File

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

View File

@@ -1,10 +1,23 @@
import { ApolloClient } from '@apollo/client';
import cache from './cache';
import createLink from './link';
import appConfig from 'config/app';
type CreateClientOptions = {
onError?: (message: string) => void;
};
const client = new ApolloClient({
uri: appConfig.graphqlUrl,
cache
cache,
link: createLink({ uri: appConfig.graphqlUrl })
});
export function setLink({ onError }: CreateClientOptions) {
const link = createLink({ uri: appConfig.graphqlUrl, onError });
client.setLink(link);
return client;
};
export default client;

View File

@@ -0,0 +1,31 @@
import { HttpLink, from } from "@apollo/client";
import { onError } from "@apollo/client/link/error";
type CreateLinkOptions = {
uri: string;
onError?: (message: string) => void;
};
const createHttpLink = (uri: CreateLinkOptions['uri']) => new HttpLink({ uri });
const createErrorLink = (callback: CreateLinkOptions['onError']) => onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) => {
callback?.(message);
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
);
});
if (networkError) {
callback?.(networkError.toString())
console.log(`[Network error]: ${networkError}`);
}
});
const createLink = ({ uri, onError = function() {} }: CreateLinkOptions) => {
return from([createErrorLink(onError), createHttpLink(uri)]);
};
export default createLink;

View File

@@ -10,19 +10,19 @@ import routes from 'routes';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<SnackbarProvider>
<ApolloProvider>
<IntlProvider>
<ThemeProvider>
<SnackbarProvider>
<Router>
<Layout>
{routes}
</Layout>
</Router>
</SnackbarProvider>
</ThemeProvider>
</IntlProvider>
</ApolloProvider>,
</ApolloProvider>
</SnackbarProvider>,
document.getElementById('root')
)