Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
import React from 'react'
import { ComponentType } from 'react'
import { LoadableContext } from './LoadableContext'
import { AsyncRequire } from './typings'

function loadable<Type = ComponentType>(asyncRequire: AsyncRequire<Type>) {
  const scoped = new LoadableContext<Type>(asyncRequire)

  if (typeof window !== 'object') {
    scoped.init()
  }

  /**
   * @todo could simply scope this
   * & pass in the loading as a prop for better @@perf?
   */
  return class Component extends React.PureComponent<any> {
    static debugName = 'CodeSplit'

    componentWillMount() {
      if (scoped.isLoaded === false) {
        const onLoad = () => {
          console.debug('[code-splitting] onLoad: ', scoped.componentName)
          this.forceUpdate()
        }

        scoped.wait().then(onLoad)
      }
    }

    render() {
      console.debug('[code-splitting] render')

      if (scoped.isLoaded === false) {
        return 'loading'
      } else if (!scoped.resolved) {
        console.log(this)
        return 'error!'
      } else {
        return React.createElement(scoped.resolved as any, this.props)
      }
    }
  }
}

export { loadable }
export default loadable