Skip to content

Instantly share code, notes, and snippets.

@EmmanuelDemey
Created November 30, 2023 09:53
Show Gist options
  • Save EmmanuelDemey/04caa88046a6772fe086afb1d7c0aba2 to your computer and use it in GitHub Desktop.
Save EmmanuelDemey/04caa88046a6772fe086afb1d7c0aba2 to your computer and use it in GitHub Desktop.
import React, { ReactElement, useContext, useEffect } from 'react';
import { useHistory } from 'react-router';
import './ErrorBoundaries.scss';
import { useT } from 'talkr';
const ErrorStatusContext = React.createContext((e: string) => {
//this is intentional
});
// How to use it => const throwError = useAsyncError(); throwError("
export const useAsyncError = () => {
const { T } = useT();
const callback = useContext(ErrorStatusContext);
return React.useCallback(
(e) => {
console.error(e.message || e);
// @ts-ignore
callback(T(e.message || e));
},
[callback, T]
);
};
export default function ErrorBoundaries({
children
}: {
children: ReactElement;
}) {
const history = useHistory();
const [error, setError] = React.useState<string | undefined>('');
const contextPayload = React.useMemo(() => setError, [setError]);
useEffect(() => {
const interval = setInterval(() => {
setError('');
}, 3000);
return () => clearInterval(interval);
}, [error]);
useEffect(() => {
// Listen for changes to the current location && cleanup the listener on unmount
return history.listen(() => setError(undefined));
}, [history]);
return (
<ErrorStatusContext.Provider value={contextPayload}>
{error && <div className="errorBlock">{error}</div>}
{children}
</ErrorStatusContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment