Skip to content

Commit

Permalink
fix(component): do not call ref several times
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Oct 30, 2018
1 parent 10b7e36 commit 8cf3190
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 16 deletions.
44 changes: 31 additions & 13 deletions packages/component/src/createLoadable.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const withLoadableState = Component => props => (

const identity = v => v

function createLoadable({ resolve = identity, render }) {
function createLoadable({ resolve = identity, render, onLoad }) {
function loadable(loadableConstructor, options = {}) {
const ctor = resolveConstructor(loadableConstructor)

Expand Down Expand Up @@ -89,33 +89,51 @@ function createLoadable({ resolve = identity, render }) {
}

componentDidMount() {
if (!this.state.result || !this.state.error) {
if (this.state.loading) {
this.loadAsync()
} else if (!this.state.error) {
this.triggerOnLoad()
}
}

triggerOnLoad() {
if (onLoad) {
setTimeout(() => {
onLoad(this.state.result, this.props)
})
}
}

loadSync() {
if (!this.state.loading) return

try {
const loadedModule = ctor.requireSync(this.props)
this.state.result = resolve(loadedModule, { Loadable })
const result = resolve(loadedModule, { Loadable })
this.state.result = result
this.state.loading = false
} catch (error) {
this.state.error = error
}
}

loadAsync() {
return ctor
.requireAsync(this.props)
.then(loadedModule => {
this.setState({
result: resolve(loadedModule, { Loadable }),
loading: false,
this.promise =
this.promise ||
ctor
.requireAsync(this.props)
.then(loadedModule => {
this.setState(
{
result: resolve(loadedModule, { Loadable }),
loading: false,
},
() => this.triggerOnLoad(),
)
})
.catch(error => {
this.setState({ error, loading: false })
})
})
.catch(error => {
this.setState({ error, loading: false })
})
}

render() {
Expand Down
7 changes: 4 additions & 3 deletions packages/component/src/library.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
import createLoadable from './createLoadable'

const library = createLoadable({
render({ result, loading, props, error }) {
if (!loading && !error && props.ref) {
onLoad(result, props) {
if (result && props.ref) {
if (typeof props.ref === 'function') {
props.ref(result)
} else {
props.ref.current = result
}
}

},
render({ result, loading, props }) {
if (!loading && props.children) {
return props.children(result)
}
Expand Down

0 comments on commit 8cf3190

Please sign in to comment.