UNPKG

react-native-filament

Version:

A real-time physically based 3D rendering engine for React Native

53 lines (51 loc) 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDisposableResource = void 0; var _react = require("react"); var _withCleanupScope = require("../utilities/withCleanupScope"); const emptyStaticArray = []; /** * Any resource that is a {@link PointerHolder} and can be released, should be loaded * using this hook. It takes care of properly releasing the resource when the component * unmounts or dependencies change. * There are certain cases like "fast refresh" or StrictMode that make useEffects execute * multiple times. Also loading the resource can be async and this hooks handles all these * cases properly. */ const useDisposableResource = (initialize, deps) => { const [resource, setResource] = (0, _react.useState)(); (0, _react.useEffect)(() => { var _initialize; let isValid = true; let currentAsset; (_initialize = initialize()) === null || _initialize === void 0 || _initialize.then(a => { if (a == null) return; if (isValid) { // this useEffect is still mounted setResource(a); currentAsset = a; } else { // this useEffect has been unmounted already, drop the asset a.release(); } }); // TODO: catch is broken // .catch((e) => { // console.error('Error while loading resource', e) // }) return () => { setResource(undefined); isValid = false; (0, _withCleanupScope.withCleanupScope)(() => { var _currentAsset; (_currentAsset = currentAsset) === null || _currentAsset === void 0 || _currentAsset.release(); })(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps ?? emptyStaticArray); return resource; }; exports.useDisposableResource = useDisposableResource; //# sourceMappingURL=useDisposableResource.js.map