Search code examples
reactjsthree.jsgltfreact-three-fiber

Trying to load the gltf link from the mongodb database in react three fiber


i have been trying to load my gltf file from the database but its not working. I tried creating separate page for model.js but still no result. Searching for the solution online alot but no sucess. Please help. the code is below:

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux'

import { Canvas } from "@react-three/fiber";
import { useGLTF } from '@react-three/drei'
import { useLoader } from "@react-three/fiber";
import { Environment, OrbitControls } from "@react-three/drei";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { Suspense } from "react";

import {
  listModelDetails
} from '../actions/ModelActions'


  const Model = () => {
    const gltf = useLoader(GLTFLoader, `/${model.content}`);
    return <primitive object={gltf} scale={0.005} />;
  }


export default function ModelScreen({ history, match }) {

const dispatch = useDispatch()

const ModelDetails = useSelector((state) => state.ModelDetails)
const { error, model } = ModelDetails


useEffect(() => {

  if (!course._id || model._id !== match.params.id) {
    dispatch(listModelDetails(match.params.id))
    
  }
}, [dispatch, match])

  return (
    <>
      <div style={{width: '70vw', height: '70vh'}}>
        <Canvas>
          <Suspense>
            <Model />
            <OrbitControls />
            <Environment preset="sunset" background />
          </Suspense>
        </Canvas>
      </div>  
    </>
  );
}

Solution

  • in HomeScreen.js (where there is model list):

     <>
              <h1>Top Courses</h1>
              <Row>
                {courses.map((course) => (
                  <Col key={course._id} xs={6} md={6} lg={4} xl={3} height='100'>
                    <Course course={course} />
                  </Col>
                ))}  
              </Row>            
            </>
    

    in ModelScreen.js(where we actually load the model):

    const Model = ({ url }) => {
      const gltf = useLoader(GLTFLoader, `${url}`);
      return <primitive object={gltf.scene} scale={0.4} />;
    };
    
     return (
        <>
          <div style={{width: '70vw', height: '70vh'}}>
            <Canvas>
              <Suspense fallback={null}>
                <Model url={course.content} />
                <OrbitControls autoRotate />
                <Environment preset="sunset" background />
              </Suspense>
            </Canvas>
          </div>
          <Meta title={course.name} />
          <h2>{course.name}</h2>
          <br />
          <br />
          <h3>Description:</h3>
          <h3>{course.description}</h3>
        </>
        
      );
    }
    

    of course there are bits i have left out. But i think its easier for you to do it! Good luck!