When using #react-three/drei useGLTF crashes scene - javascript

Hi everyone I'm kind of driving myself crazy with this, but I am trying to set up a simple three.js scene, however when I try to use the useGLTF function from #react-three/drei the scene crashes, and my console says:
Warning: meshopt_decoder is using experimental SIMD support
The above error occurred in the <ForwardRef(Canvas)> component:
at Canvas (http://localhost:3000/_next/static/chunks/pages/index.js?ts=1630506543315:10124:3)
at div
at Layout (http://localhost:3000/_next/static/chunks/pages/index.js?ts=1630506543315:502:23)
at Home
at wrappedComponent (http://localhost:3000/_next/static/chunks/pages/_app.js?ts=1630506543315:457:73)
at wrappedComponent (http://localhost:3000/_next/static/chunks/pages/_app.js?ts=1630506543315:457:73)
at ErrorBoundary (http://localhost:3000/_next/static/chunks/main.js?ts=1630506543315:764:47)
at ReactDevOverlay (http://localhost:3000/_next/static/chunks/main.js?ts=1630506543315:880:23)
at Container (http://localhost:3000/_next/static/chunks/main.js?ts=1630506543315:8865:5)
at AppContainer (http://localhost:3000/_next/static/chunks/main.js?ts=1630506543315:9361:24)
at Root (http://localhost:3000/_next/static/chunks/main.js?ts=1630506543315:9500:25)
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
THREE.WebGLRenderer: Context Lost.
My react scene looks like this:
import React, { Suspense } from 'react'
import { Canvas } from '#react-three/fiber'
import Layout from '../components/layout'
import { Sky, OrbitControls, useGLTF } from '#react-three/drei'
const Skull = () => {
const { nodes, materials } = useGLTF('skull.gltf')
console.log(nodes)
return (
<Suspense fallback={null}>
<mesh geometry={nodes.mesh_0.geometry} />
</Suspense>
)
}
export default function Home() {
return (
<Layout>
<Canvas>
<Sky sunPosition={[0, 1, 0]} />
<Skull />
<OrbitControls />
</Canvas>
</Layout>
)
}
And my packages:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#material-ui/core": "^4.12.3",
"#material-ui/lab": "^4.0.0-alpha.60",
"#react-three/drei": "^7.5.0",
"#react-three/fiber": "^7.0.6",
"add": "^2.0.6",
"axios": "^0.21.1",
"mobx": "^6.3.2",
"mobx-react": "^7.2.0",
"next": "11.1.2",
"react": "17.0.2",
"react-dom": "17.0.2",
"sass": "^1.38.2",
"three": "^0.132.2",
"three-stdlib": "^2.4.0",
"yarn": "^1.22.11"
},
"devDependencies": {
"esbuild-loader": "^2.15.1",
"eslint": "7.32.0",
"eslint-config-next": "11.1.2"
}
}
I can't figure out what is going on here and the console errors are not descriptive enough for me to understand. Is there some obvious step I am missing here?
Thanks!

I was eventually able to figure out a way to get everything to work. I had to add a call to preload the gltf file and then everything ran okay. I updated my default component to look like this:
export default function Home() {
useGLTF.preload("skull.gltf")
return (
<Layout>
<Canvas>
<Sky sunPosition={[0, 1, 0]} />
<Skull />
<OrbitControls />
</Canvas>
</Layout>
)
}
After this I got no errors loading the scene and everything worked as intended.

Related

When I add progress bar it throws Module not found: Error: Can't resolve in React

I'm new on React and I'm stuck on something. I added a new component as a 'react-customizable-progressbar' in my project. I have the following files in yellow. These were the ones that I created.
The problem point to
ERROR in ./src/example1.js 6:0-73
Module not found: Error: Can't resolve './CircularProgressBarContainer' in 'C:\Alex Maricoiu\Projects\React projects\project1\src'
Failed to compile.
CircularProgressBarContainer.tsx have the following code:
import React, {FunctionComponent} from "react";
import ICustomIndicatorProperties from './IProgressBarProperties';
import ProgressBar from 'react-customizable-progressbar'
const CustomProgressIndicator : FunctionComponent<ICustomIndicatorProperties> = ({value, title}) => {
return (
<div className="text-and-value" style={{width: "29em"}}>
<div className="title-text">{title}</div>
<div className="custom-progress-bar">
<ProgressBar
radius={100}
progress={value}
strokeWidth={18}
strokeColor="#5d9cec"
strokeLinecap="square"
trackStrokeWidth={18}
>
<div className="indicator">
<div>{value}%</div>
</div>
</ProgressBar>
</div>
</div>
)
};
export default CustomProgressIndicator;
Example1.js:
import {useState} from 'react';
import {CustomProgressIndicator} from './CircularProgressBarContainer';
function Button(props) {
return (
<button onClick={props.onClickFunc}>
Increment by 1
</button>
);
}
function Display(props){
// eslint-disable-next-line no-undef
const [counter, setCounter] = useState(0);
const incrementValue = () => setCounter(counter+1);
return (
<div>
<Button onClickFunc={incrementValue}/>
<b> Current value is: {counter}</b>
<CustomProgressIndicator
value={counter}
title ='Indicator Exercise 1'
/>
</div>
)
}
function App(props){
return (
<div>
<Display />
</div>
)
}
export default App;
The Interface file has (IProgressBarProperties.tsx):
interface ICustomIndicatorProperties {
title: string;
value: number;
}
export default ICustomIndicatorProperties;
And Main.js:
import './Main.css';
import Example1 from './example1';
import { Component } from 'react';
class App extends Component {
render(){
return (
<>
<div className='header'>Alex React Examples</div><div className='content'>
<h3>Example #1</h3>
<div id='example1Node'>
<Example1 />
</div>
</div>
</>
);
}
}
export default App;
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import MainApp from './Main';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<MainApp />
</React.StrictMode>
);
package.json:
{
"name": "project1",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-customizable-progressbar": "^1.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Thank you in advance
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Try replacing import {CustomProgressIndicator} from './CircularProgressBarContainer'; with import CustomProgressIndicator from './CircularProgressBarContainer';, since you are using export default. Curly braces are used for normal (non-default) export. Alternatively remove default from export default.
UPDATE/RESOLVE
I came back with a solution. After I investigate a little seems that there was a incorrect path to the local module created (to the local TSX file).
The UPDATE was in Example1.js. When I put the path, intellisense show me the correct way to import and I hit Enter in order to complete the path. Fine for this. The import looked like this
import {CustomProgressIndicator} from './CircularProgressBarContainer';
The problem was just right here. I correct like it is bellow and it worked.
import {CustomProgressIndicator} from './CircularProgressBarContainer.tsx';
The final result is this. The component marked in yellow was the problem.
Thank you everyone.

Next.js server keeps runing but nothing is being displayed in the browser for about 20 minutes

I'm developing this application with Next.js i'm using typescript as a language. I'm also using module css to style my components. I initialized my next application by running the following command:
yarn create next-app .
Then few days back the application was running fine but not smoothly though. I'm using window 10 [Windows [Version 10.0.19042.1165] and my node version is v14.17.5 I'm also using yarn v1.22.10. I always face this problem when my next application grows large when I run:
yarn run dev
I get this:
yarn run v1.22.10
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from ....
info - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
event - compiled successfully
event - build page: /
wait - compiling...
event - build page: /
but there's nothing that is displayed in the browser for more than 20 min the page will be loading and loading and loading. I'm thinking of changing to use gastby but i can't restart the whole process. If someone knows how to help me please help Here is my package.json file:
{
"name": "app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#apollo/client": "^3.4.10",
"#material-ui/core": "^4.12.3",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.60",
"axios": "^0.21.1",
"firebase": "^9.0.0",
"graphql": "^15.5.2",
"next": "11.1.0",
"node-sass": "4.14.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-icons": "^4.2.0",
"react-redux": "^7.2.4",
"redux": "^4.1.1"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-config-next": "11.1.0",
"typescript": "^4.4.2"
}
}
Here is my index.tsx aka my home / code if it may make sense
import { NextPage } from "next";
import React from "react";
import styles from "../styles/Home.module.css";
import Header from "../components/minor/flesh/Header/Header";
import HeaderSkeleton from "../components/minor/skeletons/components/Header/HeaderSkeleton";
import Fleets from "../components/minor/flesh/Fleets/Fleets";
import FleetsSkeleton from "../components/minor/skeletons/components/Fleets/FleetsSkeleton";
import Form from "../components/minor/flesh/Form/Form";
import { IoIosCreate } from "react-icons/io";
import { IconButton } from "#material-ui/core";
import { ThemeType } from "../types/major";
import FormSkeleton from "../components/minor/skeletons/components/Form/FormSkeleton";
import { useQuery } from "#apollo/client";
import HELLO_WORLD_QUERY from "../graphql/queries/hello/hello";
import Post from "../components/minor/flesh/Post/Post";
import { useSelector } from "react-redux";
import PostSkeleton from "../components/minor/skeletons/components/Post/PostSkeleton";
import { apolloClient } from "../lib/apolloClient";
import USER_QUERY from "../graphql/queries/user/user";
import { useRouter } from "next/router";
interface Props {
data: any;
}
const Home: NextPage<Props> = ({ data }) => {
data = JSON.parse(data);
const router = useRouter();
const [showForm, setShowForm] = React.useState(false);
const theme = useSelector((state: any) => state.theme);
const className: string = `${styles.app} ${
theme === "dark" ? styles.dark__theme : styles.light__theme
}`;
return (
<div className={className}>
{/* <Header theme="light" /> */}
<HeaderSkeleton theme={theme} />
{/* <FormSkeleton theme={theme} /> */}
{showForm ? <Form theme={theme} setShowForm={setShowForm} /> : null}
<div className={styles.app__main}>
<Fleets theme={theme} />
<FleetsSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
</div>
<IconButton title="new post" onClick={() => setShowForm(true)}>
<IoIosCreate className={styles.home__create__post__icon} />
</IconButton>
</div>
);
};
Home.getInitialProps = async (context) => {
const user = await apolloClient.query({
query: USER_QUERY,
});
if (!user.data?.user) {
context.res.writeHead(307, { Location: "http://localhost:3000/welcome" });
return {
data: null,
};
}
return {
data: JSON.stringify(user, null, 2),
};
};
export default Home;
I am not sure, but it seems to work in my case. When I start server with different port (not the default 3000) it works just fine next dev -p 1234
Running it in an incognito window worked for me
Do a hard reload (Ctrl + Shift + R) if not running on port 3000.
I just had this same issue, localhost:3000 wasn't showing anything for about 15 minutes.
Please check if you made changes to your config file, "I hadn't". So I fixed it by going to next.cofig.js file and pressing Ctrl + Z, but changed nothing. This tricked Next.js to think there's a change in there.
Then I restarted the server and it displayed fine.
Just hit Ctrl + click on http://localhost:3000 from terminal.
You will get the below result to perform the above operation in the terminal after yearn dev or npm run dev.
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 357 ms (154 modules)
Try to rewrite your _app.js file. It can help to resolve your problem.
I'm using next.js with TypeScript and Material UI.
You can use the following code and replace that.
// pages/_app.tsx
import * as React from 'react';
import Head from 'next/head';
import { AppProps } from 'next/app';
import { ThemeProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline';
import { CacheProvider, EmotionCache } from '#emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
interface MyAppProps extends AppProps {
emotionCache?: EmotionCache;
}
export default function MyApp(props: MyAppProps) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
return (
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
);
}

Using any form of the Map function with react causes an undefined error

After reducing my code to the simplest of forms it looks like I have an un-resolvable problem with the map function used anywhere in any location.
I know code in examples which runs on Codepen etc doesn't work with create react app project locally, so I'm wondering if there is an issue with the build setup.
I'm new to react, and haven't been actively programming for about 4-5 years, so its very possible I am at fault
Error is the iterator parameter within the map having an undefined value: 'd' below in this and the days worth of writing similar code to find a solution
The code is as follows after reducing it to its simplest form
Code which doesn't work in my build works on codepen.
I've tried props, state class or block variables
I've tried nested functions, as well as => functions
I've tried with different classes different variables, and the error is always exactly the same
import { React, Component } from 'react';
class ProtoList extends Component {
constructor(props) {
super(props)
this.state = {
};
}
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
let listItems = data.map(d =>
<span key={d.name}>{d.name}</span>
)
return listItems;
}}
export default ProtoList;
import React from 'react';
import Container from '#material-ui/core/Container';
import { makeStyles } from '#material-ui/core/styles';
import WebHeader from './components/WebHeader';
import WebMain from './components/WebMain';
import WebFooter from './components/WebFooter';
import ProtoList from './components/ProtoList';
const useStyles = makeStyles(theme => ({
root: {
minHeight: '500px',
paddingLeft: '0px',
paddingRight: '0px',
backgroundColor: '#001e1c',
},
}));
export default function App() {
const classes = useStyles();
return (
<ProtoList />
/*
<Container className={classes.root}>
<WebHeader />
<WebMain />
<WebFooter />
</Container>
*/
);
}
Package:
{
"name": "telescout-pr2",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.22",
"#fortawesome/free-brands-svg-icons": "^5.10.2",
"#fortawesome/react-fontawesome": "^0.1.4",
"#material-ui/core": "^4.3.3",
"#material-ui/icons": "^4.2.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1",
"react-vis": "^1.11.7",
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint": "^6.2.2",
"eslint-plugin-react": "^7.14.3"
}
}
TypeError: Cannot read property 'createElement' of undefined
(anonymous function)
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
> let listItems = data.map(d =>
<span key={d.name}>{d.name}</span>
)
return listItems;
The createElement method is the primary method React uses to build components, it's undefined because the React object isn't being imported:
import React, { Component } from 'react';
Cheers!
Try this
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
return (
<>
{data.map(d => <span key={d.name}>{d.name}</span>}
</>
);
}}
If you are returning an array of elements, they must be wrapped in a JSX element.
Also, just a tip on React. If you aren't using state, make it a functional component, not a class component.

How can I use a React component within a Node script?

I'm currently trying to use react-pdf to generate and save a pdf to disk. Rendering to a webpage works, but the method that I need to invoke to save a pdf to disc,
ReactPDF.render()
does not work within the npm start (react-scripts) way of running React that I've used in the past to create webpages. From reading this issue, it seems that it needs to be run as a "Node only api". So my question is, what dependencies, commands, and steps do I need to take to run some react code and save a pdf to disk with something like
> node index.js
currently when I run the above command I get
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
Then, running
node --experimental-modules index.mjs
I get
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
^
SyntaxError: Unexpected token <
Here are my two files:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ReactPDF from '#react-pdf/renderer';
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
//ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React, { Component } from 'react';
import { Document, Page, Text, View, StyleSheet } from '#react-pdf/renderer'
class App extends Component {
render() {
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
}
}
export default App;
package.json
{
"name": "ccv-generator-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#react-pdf/renderer": "^1.4.2",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-scripts": "2.1.8",
"ts-pnp": "^1.0.1",
"typescript": "^3.3.4000"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
A follow up question would be, Is what I am trying to do an anti-pattern?
Since you're running index.mjs directly from node, it does not go through the build and transpilation process of react-scripts, meaning you have to do it manually.
Node cannot directly parse jsx (<App/>, for example) - so you will need to run your code through Babel with React preset in order to run it.
Since the dependecies should be already installed, try running:
npx babel index.mjs -o index-compiled.js --presets=es2015,react
and then run the compiled file:
node index-compiled.js

Why am I getting "TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function" error when using reactjs hooks?

I'm trying to use this component straight from the Material Ui (Simple Menu https://material-ui.com/demos/menus/#menus) docs in order to make a menu appear. However, I'm getting TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function error with my current attempt below. I tried:
import React, { useState } from 'react'; and then got rid of React inside const [anchorEl, setAnchorEl] = React.useState(null); to make it look like: const [anchorEl, setAnchorEl] = useState(null);
I also tried replacing null with a number but still got same error.
Note: Another attempt installed the right packages and made my package.json file look like this (TypeError dispatcher.useState is not a function when using React Hooks):
{
"name": "speedy-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.9.0",
"#material-ui/icons": "^3.0.2",
"classnames": "^2.2.6",
"node-sass": "^4.11.0",
"prop-types": "^15.6.2",
"react": "16.7.0-alpha.0",
"react-dom": "16.7.0-alpha.0",
"react-test-renderer": "16.7.0-alpha.0",
"react-scripts": "2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Screen shot of error:
What am I doing wrong and how can I fix it?
import React from 'react';
import Button from '#material-ui/core/Button';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
const SimpleMenu = () => {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<Button
aria-owns={anchorEl ? 'simple-menu' : undefined}
aria-haspopup="true"
onClick={handleClick}
>
Open Menu
</Button>
<Menu id="simple-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
};
export default SimpleMenu;
While I'm not sure what is wrong in the code above (my guess is using a non-release build of material-ui in which an export was not default as it documentation states), this error occurred for me with improper imports. My issue was that I was trying to
import someNonDefaultFunction from 'someModule';
Adding the braces around the named/non-default import resolved the same error message for me:
import {someNonDefaultFunction} from 'someModule';

Categories

Resources