React: React.lazy: Not recognizing named modules resolved through .then()

Created on 25 Oct 2018  路  4Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Named components that have been extracted in a .then() call are not being recognized.

const NamedExport = React.lazy(() =>
  import("./NamedExport")
    .then(module => module.NamedExport)
    .then(component => {
      console.log(component)
      return component
    })
)

The code above is generating the error below despite the fact that the named export gets logged to the console correctly.

Invariant Violation
Element type is invalid. Received a promise that resolves to: undefined. Promise elements must resolve to a class or function.

Link to codesandbox example

What is the expected behavior?

This should render the component correctly

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

react 16.6.0
react-dom 16.6.0

MacOS 10.14 Version 69.0.3497.100

React.lazy was not in previous versions of React

Most helpful comment

Just return {default: component} will work fine(But this is a hack, I think you should not do this and don't add .then at least for now).

https://reactjs.org/docs/code-splitting.html#reactlazy :

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.

If you want to get more info about this, you could read https://github.com/reactjs/rfcs/pull/64

All 4 comments

Just return {default: component} will work fine(But this is a hack, I think you should not do this and don't add .then at least for now).

https://reactjs.org/docs/code-splitting.html#reactlazy :

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.

If you want to get more info about this, you could read https://github.com/reactjs/rfcs/pull/64

Yeah it's not intended to work right now.

Ack - I missed that. My bad. The error message could probably at least be improved. Received a promise that resolves to: undefined. is misleading.

use async may solve your problem

const NamedExport = React.lazy(async () =>
  import("./NamedExport")
    .then(module => module.NamedExport)
    .then(component => {
      console.log(component)
      return component
    })
)
Was this page helpful?
0 / 5 - 0 ratings