Skip to content

Instantly share code, notes, and snippets.

@tylervipond
Created August 4, 2020 02:37
Show Gist options
  • Save tylervipond/641b2cde8b45ad0e991668cec60478d7 to your computer and use it in GitHub Desktop.
Save tylervipond/641b2cde8b45ad0e991668cec60478d7 to your computer and use it in GitHub Desktop.
// src/useWasm.js
export const useWasm = (fileName, imports) => {
  const [state, setState] = useState({
    loaded: false,
    instance: null,
    error: null,
  });
  useEffect(() => {
+   const abortController = new AbortController();
    const fetchWasm = async () => {
      try {
-       const wasm = await fetch(fileName);
+       const wasm = await fetch(
+         fileName,
+         { signal: abortController.signal }
+       );
        if (!wasm.ok) {
          throw new Error(`Failed to fetch resource ${fileName}.`);
        }
        const instance = await AsBind.instantiate(wasm, imports);
-       setState({instance, loaded:true, error: null});
+       if (!abortController.signal.aborted) {
+         setState({instance, loaded:true, error: null});
+       }
      } catch (e) {
-       setState({...state, error: e });
+       if (!abortController.signal.aborted) {
+         setState({...state, error: e });
+       }
      }
    }
    fetchWasm();
+   return function cleanup() {
+     abortController.abort();
+   };
  }, [fileName, imports]);
  return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment