Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abort image requests on unmount #624

Merged
merged 1 commit into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 44 additions & 12 deletions src/components/util/SpinnerImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import { Theme, SxProps, Stack, Button } from '@mui/material';
import BrokenImageIcon from '@mui/icons-material/BrokenImage';
import RefreshIcon from '@mui/icons-material/Refresh';
import { useTranslation } from 'react-i18next';
import { CanceledError } from 'axios';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { defaultPromiseErrorHandler } from '@/util/defaultPromiseErrorHandler.ts';

interface IProps {
src: string;
Expand All @@ -32,6 +35,7 @@ export function SpinnerImage(props: IProps) {

const { t } = useTranslation();

const [imageSourceUrl, setImageSourceUrl] = useState('');
const [imgLoadRetryKey, setImgLoadRetryKey] = useState(0);
const [isLoading, setIsLoading] = useState<boolean | undefined>(undefined);
const [hasError, setHasError] = useState(false);
Expand All @@ -46,28 +50,54 @@ export function SpinnerImage(props: IProps) {
};

useEffect(() => {
// only activate the loading state in case the image has not been cached yet.
// otherwise, the loading placeholder will always be visible before the actual image is shown, which looks like flickering
const timeout = setTimeout(() => setIsLoading((prevState) => (prevState === undefined ? true : prevState)), 1);
return () => clearTimeout(timeout);
}, []);
const imageRequest = requestManager.requestImage(src);

const fetchImage = async () => {
try {
const updateImage = async () => {
const image = await imageRequest.response;

updateImageState(false);
setImageSourceUrl(image);
};

const checkCache = await Promise.race([imageRequest.response, Promise.resolve(false)]);
const isImageCached = !!checkCache;

if (isImageCached) {
await updateImage();
return;
}

updateImageState(true);
await updateImage();
} catch (e) {
const wasAborted = e instanceof CanceledError;
updateImageState(false, !wasAborted);
}
};

fetchImage().catch(defaultPromiseErrorHandler);

return () => {
imageRequest.abortRequest(new Error('Component was unmounted'));
};
}, [imgLoadRetryKey]);

return (
<>
{(isLoading || hasError) && (
<Box sx={spinnerStyle}>
<Stack height="100%" alignItems="center" justifyContent="center">
{isLoading && <CircularProgress thickness={5} />}
{hasError && (
{hasError && isLoading === false && (
<>
<BrokenImageIcon />
<Button
startIcon={<RefreshIcon />}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setIsLoading(true);
setHasError(false);
setImgLoadRetryKey((prevState) => (prevState + 1) % 100);
}}
size="large"
Expand All @@ -79,14 +109,16 @@ export function SpinnerImage(props: IProps) {
</Stack>
</Box>
)}

<img
key={`${src}_${imgLoadRetryKey}`}
style={{ ...imgStyle, display: isLoading || hasError ? 'none' : imgStyle?.display }}
style={{
...imgStyle,
display: !imageSourceUrl || isLoading || hasError ? 'none' : imgStyle?.display,
}}
ref={imgRef}
src={src}
src={imageSourceUrl}
alt={alt}
onLoad={() => updateImageState(false)}
onError={() => updateImageState(false, true)}
draggable={false}
/>
</>
Expand Down
12 changes: 12 additions & 0 deletions src/lib/requests/RequestManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,18 @@ export class RequestManager {
return `${this.getValidUrlFor(imageUrl, apiVersion)}`;
}

public requestImage(url: string): { response: Promise<string> } & AbortableRequest {
const { abortRequest, signal } = this.createAbortController();
const response = this.restClient
.fetcher(url, {
checkResponseIsJson: false,
config: { signal, responseType: 'blob' },
})
.then((data) => URL.createObjectURL(data));

return { response, abortRequest };
}

private doRequest<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.QUERY,
operation: DocumentNode | TypedDocumentNode<Data, Variables>,
Expand Down
Loading