Skip to content

Commit

Permalink
fix(useLoader): dispose loaders (#2984)
Browse files Browse the repository at this point in the history
  • Loading branch information
CodyJasonBennett authored Sep 3, 2023
1 parent 23da88a commit ff3c86b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 19 deletions.
11 changes: 9 additions & 2 deletions packages/fiber/src/core/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,20 @@ export function useGraph(object: THREE.Object3D) {
return React.useMemo(() => buildGraph(object), [object])
}

const memoizedLoaders = new WeakMap<LoaderProto<any>, Loader<any>>()

function loadingFn<L extends LoaderProto<any>>(
extensions?: Extensions<L>,
onProgress?: (event: ProgressEvent<EventTarget>) => void,
) {
return function (Proto: L, ...input: string[]) {
// Construct new loader and run extensions
const loader = new Proto()
let loader = memoizedLoaders.get(Proto)!
if (!loader) {
loader = new Proto()
memoizedLoaders.set(Proto, loader)
}

if (extensions) extensions(loader)
// Go through the urls and load them
return Promise.all(
Expand All @@ -103,7 +110,7 @@ function loadingFn<L extends LoaderProto<any>>(
),
),
),
)
).finally(() => (loader as any).dispose?.())
}
}

Expand Down
32 changes: 15 additions & 17 deletions packages/fiber/tests/core/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,25 +138,21 @@ describe('hooks', () => {
mesh2.name = 'Mesh 2'
MockGroup.add(mesh1, mesh2)

jest.spyOn(Stdlib, 'GLTFLoader').mockImplementation(
() =>
({
load: jest
.fn()
.mockImplementationOnce((_url, onLoad) => {
onLoad(MockMesh)
})
.mockImplementationOnce((_url, onLoad) => {
onLoad({ scene: MockGroup })
}),
setPath: () => {},
} as unknown as Stdlib.GLTFLoader),
)
class TestLoader extends THREE.Loader {
load = jest
.fn()
.mockImplementationOnce((_url, onLoad) => {
onLoad(MockMesh)
})
.mockImplementationOnce((_url, onLoad) => {
onLoad(MockGroup)
})
}

const extensions = jest.fn()

const Component = () => {
const [mockMesh, mockScene] = useLoader(Stdlib.GLTFLoader, ['/suzanne.glb', '/myModels.glb'], (loader) => {
loader.setPath('/public/models')
})
const [mockMesh, mockScene] = useLoader(TestLoader, ['/suzanne.glb', '/myModels.glb'], extensions)

return (
<>
Expand All @@ -180,6 +176,8 @@ describe('hooks', () => {
await waitFor(() => expect(scene.children[0]).toBeDefined())

expect(scene.children[0]).toBe(MockMesh)
expect(scene.children[1]).toBe(MockGroup)
expect(extensions).toBeCalledTimes(1)
})

it('can handle useLoader with a loader extension', async () => {
Expand Down

0 comments on commit ff3c86b

Please sign in to comment.