From b8b94230d7614eb2afdf7db72debff0868b8183e Mon Sep 17 00:00:00 2001 From: Mauve Date: Wed, 22 Apr 2020 17:11:23 -0400 Subject: [PATCH] Add support for placeholder function --- docs/Details.md | 6 +++--- modules/Coroutine.js | 9 ++++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/Details.md b/docs/Details.md index b5d69a1..e082159 100644 --- a/docs/Details.md +++ b/docs/Details.md @@ -36,9 +36,9 @@ based on your opinion or particular task. When an async component is mounted, async function is executed. Initially, mounted component will render nothing, since async function hasn't been -resolved or rejected yet. You can set your `placeholder` for the pending state, -check Dependency Injection docs below. Once async function is resolved, the -thing it returned will be rendered instead of placeholder. Whenever you pass +resolved or rejected yet. You can set your `placeholder` for the pending state +by passing a function as the second argument. Once async function is resolved, +the thing it returned will be rendered instead of placeholder. Whenever you pass new props to an async component it will switch to pending state and execute async function again. diff --git a/modules/Coroutine.js b/modules/Coroutine.js index b4f40e0..dca76be 100644 --- a/modules/Coroutine.js +++ b/modules/Coroutine.js @@ -2,11 +2,11 @@ import { PureComponent } from 'react'; export default { create }; -function create(coroutine) { +function create(coroutine, placeholder) { class Coroutine extends PureComponent { constructor(props) { super(props); - this.state = { view: null }; + this.state = { view: null, loading: true }; this.iterator = null; } @@ -16,7 +16,7 @@ function create(coroutine) { this.iterator = target; let shouldStop = () => this.iterator !== target; - let updateView = view => this.setState({ view }); + let updateView = view => this.setState({ view, loading: false }); if (target && typeof target.then === 'function') { // coroutine is Async Function, awaiting for the final result @@ -40,6 +40,9 @@ function create(coroutine) { this.iterate(this.props); } + // Render a placeholder if we have one + if(this.state.loading && placeholder) return placeholder(this.props) + return this.state.view; } }