Skip to content

Commit

Permalink
feat: prevent multiple loads
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Jun 29, 2017
1 parent 4711875 commit 5706e21
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
20 changes: 15 additions & 5 deletions src/loadable.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,23 @@ function loadable(
) {
class LoadableComponent extends React.Component {
static Component = null
static loadingPromise = null

static load() {
return getComponent().then(module => {
const Component = resolveModuleDefault(module)
LoadableComponent.Component = Component
return Component
})
if (!LoadableComponent.loadingPromise) {
LoadableComponent.loadingPromise = getComponent()
.then(module => {
const Component = resolveModuleDefault(module)
LoadableComponent.Component = Component
return Component
})
.catch(error => {
LoadableComponent.loadingPromise = null
throw error
})
}

return LoadableComponent.loadingPromise
}

state = {
Expand Down
13 changes: 12 additions & 1 deletion src/loadable.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import Dummy from './__fixtures__/Dummy'
import loadable from './loadable'

describe('#loadable', () => {
let getComponent
let Loadable

beforeEach(() => {
Loadable = loadable(() => import('./__fixtures__/Dummy'))
getComponent = jest.fn(() => import('./__fixtures__/Dummy'))
Loadable = loadable(getComponent)
})

it('should load component using import', async () => {
Expand All @@ -19,6 +21,15 @@ describe('#loadable', () => {
expect(wrapper.contains(<Dummy />)).toBe(true)
})

it('should not load it two times', async () => {
const wrapper = mount(<Loadable />)
expect(wrapper.find('EmptyComponent').exists()).toBe(true)
Loadable.load()
await Loadable.load()
expect(getComponent).toHaveBeenCalledTimes(1)
expect(wrapper.contains(<Dummy />)).toBe(true)
})

it('should render it directly if component is already loaded', async () => {
await Loadable.load()
const wrapper = mount(<Loadable />)
Expand Down

0 comments on commit 5706e21

Please sign in to comment.