Skip to content

Commit 15531a6

Browse files
authored
Merge pull request #65 from DiamondLightSource/fix_state_update_on_unmounted_comp
Fix state update on an unmounted component
2 parents 4557f96 + 6677fde commit 15531a6

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/ui/widgets/EmbeddedDisplay/useOpiFile.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,25 +77,35 @@ export function useOpiFile(file: File): WidgetDescription {
7777
const fileExt = file.path.split(".").pop() || "json";
7878
const [contents, setContents] = useState<WidgetDescription>(EMPTY_WIDGET);
7979

80-
useEffect((): void => {
80+
useEffect(() => {
81+
let isMounted = true;
8182
const fetchData = async (): Promise<void> => {
8283
if (fetchPromises.hasOwnProperty(file.path)) {
8384
// This resource has been requested; once the cached
8485
// promise has been resolved the fileCache should be
8586
// populated.
8687
await fetchPromises[file.path];
87-
setContents(fileCache[file.path]);
88+
if (isMounted) {
89+
setContents(fileCache[file.path]);
90+
}
8891
} else {
8992
const fetchPromise = fetchAndConvert(file.path, file.defaultProtocol);
9093
// Populate the promises cache.
9194
fetchPromises[file.path] = fetchPromise;
9295
const contents = await fetchPromise;
9396
// Populate the file cache.
9497
fileCache[file.path] = contents;
95-
setContents(contents);
98+
if (isMounted) {
99+
setContents(contents);
100+
}
96101
}
97102
};
98103
fetchData();
104+
105+
// Tidy up in case component is unmounted
106+
return () => {
107+
isMounted = false;
108+
};
99109
}, [file.path, file.defaultProtocol, fileExt]);
100110

101111
return contents;

0 commit comments

Comments
 (0)