首页 > 其他 > 详细

[React] Write a generic React Suspense Resource factory

时间:2019-12-08 19:59:04      阅读:82      评论:0      收藏:0      [点我收藏+]

Using Suspense within our component isn‘t exactly ergonomic. Let‘s put all that logic into a reusable function so we can create resources anytime we need them and for any asynchronous interaction in our app.

 

In previous post, https://www.cnblogs.com/Answer1215/p/12006526.html, we have see how to use React.Suspense to handle data fetching, with fallback and ErrorBoundary. 

In this post, we will refactor code to make a generic function to handle all use cases.

function createFetch(fetchFn) {
  let status = ‘pending‘
  let result
  let error
  let promise = fetchFn().then(
    p => {
      console.log(‘promise resolve‘)
      status = ‘success‘
      result = p
    },
    e => {
      status = ‘error‘
      error = e
    },
  )

  return {
    read() {
      if (status === ‘error‘) {
        throw error
      }

      if (status === ‘pending‘) {
        throw promise // this API might change
      }

      if (status === ‘success‘) {
        return result
      }
    },
  }
}

 

Use:

const promise = createFetch(() => fetchPokemon(‘pikachu‘))

function PokemonInfo() {
  console.log(‘PokemonInfo init‘)

  const pokemon = promise.read()

  return (
    <div>
      <div className="pokemon-info__img-wrapper">
        <img src={pokemon.image} alt={pokemon.name} />
      </div>
      <PokemonDataView pokemon={pokemon} />
    </div>
  )
}

 

[React] Write a generic React Suspense Resource factory

原文:https://www.cnblogs.com/Answer1215/p/12006589.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!