Skip to content

Commit

Permalink
Fix subtle stale state issue in H5WasmProvider
Browse files Browse the repository at this point in the history
When any of the props change, `App` gets rendered once with a stale API instance.
  • Loading branch information
axelboc committed Feb 8, 2024
1 parent f344eee commit d33b6c6
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions packages/h5wasm/src/H5WasmProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { DataProviderApi } from '@h5web/app';
import { DataProvider } from '@h5web/app';
import type { PropsWithChildren } from 'react';
import { useEffect, useState } from 'react';
import { useMemo, useState } from 'react';

import { H5WasmApi } from './h5wasm-api';
import type { Plugin } from './utils';
Expand All @@ -16,17 +16,15 @@ interface Props {
function H5WasmProvider(props: PropsWithChildren<Props>) {
const { filename, buffer, getExportURL, getPlugin, children } = props;

const [api, setApi] = useState<H5WasmApi>();
const api = useMemo(
() => new H5WasmApi(filename, buffer, getExportURL, getPlugin),
[buffer, filename, getExportURL, getPlugin],
);

useEffect(() => {
const h5wasmApi = new H5WasmApi(filename, buffer, getExportURL, getPlugin);
setApi(h5wasmApi);

return () => void h5wasmApi.cleanUp();
}, [filename, buffer, getExportURL, getPlugin]);

if (!api) {
return null;
const [prevApi, setPrevApi] = useState(api);
if (prevApi !== api) {
setPrevApi(api);
void prevApi.cleanUp(); // https://github.com/silx-kit/h5web/pull/1568
}

return <DataProvider api={api}>{children}</DataProvider>;
Expand Down

0 comments on commit d33b6c6

Please sign in to comment.