Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading in react - the component is not loading

Can someone please explain why my lazy loaded component never loads?

All is see is the message loading... on the screen...and no errors.

Below is my code:

import React, { Component, lazy, Suspense } from "react";
import "./App.css";
//const Mycomp = lazy(() => import("./components/myComp"));
const Mycomp = lazy(() => {
  let x = new Promise(
    () => {
      import("./components/myComp");
    },
    e => {
      console.log(e);
    }
  );
  return x;
});

class App extends Component {
  sayHi = () => {
    console.log("supa");
  };

  render() {
    return (
      <Suspense fallback={<div> loading...</div>}>
        <div className="App">
          <header className="App-header">
            <Mycomp />
            <input type="button" value="sayHi" onClick={this.sayHi} />
          </header>
        </div>
      </Suspense>
    );
  }
}

export default App;

This is simply for learning purpose.. so please be kind.. I'm not very familiar with react in general....

below is the code for myComp.jsx:

import React, { Component } from "react";

class Mycomp extends Component {
  state = {};
  render() {
    return <div>Hi i'm loaded now.</div>;
  }
}

export default Mycomp;
like image 226
psj01 Avatar asked Dec 20 '18 01:12

psj01


1 Answers

from the react docs.

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

Now its subtle, but I think in your case you are returning your own newly created promise which you have assigned to x. You did not however specify what this promise resolves to. React needs you to return a promise which resolves to a component with a default export.

I think you can make one small change to your code to get it working.

const Mycomp = lazy(() => {
   return import("./components/myComp");
});

The dynamic import already returns a promise which resolves to a component with a default export, so I think you wrapping it in your own promise which you are returning is throwing it off.

Here is the example from the react docs.

const OtherComponent = React.lazy(() => import('./OtherComponent'));

Here is some example code showing how do add a timeout.

const OtherComponent = React.lazy(() => {
  const x = new Promise((resolve) => {
    setTimeout(() => {
      return resolve(import("./Child"))
    }, 1500)
  })
  return x;
});

class App extends Component {
  render() {
    return (
      <div className="App">
        <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
        </Suspense>
      </div>
    );
  }
}
like image 118
Chaim Friedman Avatar answered Nov 15 '22 03:11

Chaim Friedman