What is the correct way to utilize drei's useGLTF function?

Despite following the react-three docs and various examples, I am struggling to get drei useGLTF to function properly in my project.

I have a basic Next|React|react-three/fiber project that I built from scratch. My goal is to load the astronaut example and render it on the screen.

Initially, the code below seemed to work perfectly. However, after making some minor changes and reverting them, the code stopped working. I've experimented with and without Suspense, but to no avail.

import { Canvas, Suspense } from '@react-three/fiber'
import { useGLTF } from '@react-three/drei'

function Model() {
  const gltf = useGLTF('https://thinkuldeep.com/modelviewer/Astronaut.glb')
  return (<primitive object={gltf.scene} />)
}

export default function Home() {
  return (
    <div>
      {/* <Suspense> */}
        <Canvas>
          <ambientLight />
          <Model />
        </Canvas>
      {/* </Suspense> */}
    </div>
  )
}

Console message available at this link: https://i.stack.imgur.com/yYW2K.png

Below is my package.json file:

{
  "name": "cfgnext",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@react-three/drei": "^8.18.10",
    "@react-three/fiber": "^7.0.26",
    "next": "12.1.0",
    "react": "17.0.2",
    "react-dom": "^17.0.2",
    "styled-components": "^5.3.3"
  },
  "devDependencies": {
    "eslint": "8.11.0",
    "eslint-config-next": "12.1.0"
  }
}

Based on my research, this should be a straightforward task. Can anyone point out where I might be overlooking something?

Thanks in advance,
Bill

Answer №1

I recently updated my React, Fiber, and drei to the latest versions, and this update made my original code work successfully (utilizing Suspense from React). Below is the modified code with regard to Suspense:

import { Suspense } from 'react'
import { Canvas } from '@react-three/fiber'
import { useGLTF } from '@react-three/drei'

function Model() {
  const gltf = useGLTF('https://thinkuldeep.com/modelviewer/Astronaut.glb')
  return (<primitive object={gltf.scene} />)
}

export default function Home() {
  return (
    <div>
      <Suspense>
        <Canvas>
          <ambientLight />
          <Model />
        </Canvas>
      </Suspense>
    </div>
  )
}

Below are the specific versions I used for reference:

{
  "name": "cfgnext-updated",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@react-three/drei": "^9.0.1",
    "@react-three/fiber": "^8.0.6",
    "next": "12.1.4",
    "react": "18.0.0",
    "react-dom": "18.0.0"
  },
  "devDependencies": {
    "eslint": "8.12.0",
    "eslint-config-next": "12.1.4"
  }
}

Answer №2

My approach is quite similar, although I prefer to utilize Suspense in a different manner

<Suspense fallback={null}>
  <Model src={src} containerRef={containerRef.current} />
</Suspense>

In addition, I have included an error boundary to prevent any crashes during rendering

import { withErrorBoundary } from 'react-error-boundary';

// ...

export default withErrorBoundary(ModelViewer, {
  FallbackComponent: () => (<div>An error occurred</div>),
  onError: (err: Error, info: {componentStack: string}) => console.error(err, info),
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

Guide on deploying a NextJs frontend with Golang (Go) and gorilla/mux

After following a guide to serve a NextJs front-end single-page application using Golang and the native net/http package, I decided to switch to using gorilla/mux. Here is my updated main function: func main() { // Root at the `dist` folder generated ...

Ways to link my frontend to a NodeJS backend that is publicly deployed rather than on localhost

When my NodeJS server is running on localhost PORT, I can successfully connect them both by using the following code: const PORT = 9000; const app = express() app.listen(PORT, () => console.log(`Server is up and running on PORT ${PORT}`)) app.use(bodyPa ...

Is it possible to utilize the layout of a parent route for the loading screen of a sub route?

App Structure Currently, I am working with Next JS 13 and the app router. The simplified structure of my app is as follows: app -(landing) - page.js - layout.js -(results) - layout.js - loading.js - results - page.js -components - vapour ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

Next.js producing a duplicate output

While developing a web application using next js, I have encountered an issue with Router Push. It redirects to the login page successfully, but upon redirection to the login page, I am receiving double notifications. Can someone help me identify and fix t ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

What is the best way to resolve this React.js warning?

While the NotFound component is being loaded, I want to process the method I sent as props by providing a parameter value. To achieve this, I have utilized the useEffect hook. Although the desired outcome is achieved, there is a persistent warning message ...

The Material-UI theme remains consistent and does not revert back

Struggling to implement a theme in my React app using Material-UI ThemeProvider and encountering some odd behavior. I've set up two themes: day mode and night mode. Initially, the app defaults to night mode and users can switch between the two using ...

Trying out the componentWillUnmount() function to erase a class from the body element

In my React component, I have the following code: componentWillUnmount () { document.body.classList.remove('isPreloaded') } Initially, in my index.html file, I have a body tag with the class isPreloaded, along with a Preloader HTML and ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Can custom action buttons be added to mui tables?

I'm currently working on a table that pulls data from an API and presents it in either an MUI table or Material table. I would like to have different action buttons displayed for each row - for example, in the first row, the button should read "connec ...

The React Hook useEffect is missing a dependency: 'handleLogout'. Make sure to either add it to the dependency array or remove it from the useEffect hook

import { useState, useEffect } from "react"; import LoginModal from "./LoginModal"; import { NavLink, useLocation, useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { userLogout ...

The function window.require does not exist

Here is the code I wrote: const { ipcRenderer } = window.require('electron'); An error occurred: TypeError: window.require is not a function I attempted to utilize IPC communication in order to manage the Electron window using React. Regrett ...

A custom-designed Material UI TextField featuring a specific date and time picker capable of displaying seconds

Currently, I am facing an issue while using react-admin and trying to modify the date and time, specifically including seconds with the help of DateTimeInput. Unfortunately, my attempts have been unsuccessful so far. Here is what I have tried: Approach 1: ...

Unused React import in the index.js file

Just starting to explore the world of reactJS. import React from 'react'; import ReactDOM from 'react-dom'; var App = ()=>{ return <div> Hello !!</div> } ReactDOM.render(<App />, document.getElementById(' ...

Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the tru ...

What is the best way to clear a TextField in Java?

Is there a way to make the text field display empty if the column is null? Currently, when using an empty string as the value, the label appears in the position of the actual value. How can this be improved? <TextField margin="normal" ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...