pmndrs / react-three-fiber

🇨🇭 A React renderer for Three.js
https://docs.pmnd.rs/react-three-fiber
MIT License
27.62k stars 1.6k forks source link

Can we modify useLoader to accept an empty string or null? #3189

Closed taeuscherpferd closed 7 months ago

taeuscherpferd commented 8 months ago

This would be super helpful in cases where the consumer is trying to dynamically load in urls for models. For example, I have a database that contains all of my models, and I want to allow my user to select a model to load in. In this case I would have a state variable for the selected model const [modelUrl, setModelUrl] = useState("") Until my user selects a url, modelUrl will be blank which causes the useLoader() hook to fail. Yes I could wrap the object specifically in a specific component that is only added if I have a URL, but that can be obnoxious. Instead I propose that the hook early out if an empty string is provided.

Also while we're here, in my experience <ErrorBoundary>s in react are kind of unreliable and messy. It would be much cleaner if we could modify the useLoader hook (as well as it's sibling hooks) to not completely crash an app if something goes wrong with the model. Still log errors, but maybe allow for developers to handle them without using <ErrorBoundary>

Happy to make a pull request if everyone is on board with the idea

Thanks for all the hard work and awesome libraries 👍

CodyJasonBennett commented 7 months ago

I'd see #3181 for reliability of error boundaries and async errors, but we don't allow hooks to be called conditionally. You can use https://github.com/pmndrs/suspend-react conditionally as it is not a hook or React.use in the future.

import { suspend } from 'suspend-react'

function Model() {
  const model = suspend(async () => modelUrl && new GLTFLoader().loadAsync(modelUrl), [modelUrl])
}