25

GitHub - Astrocoders/epitath: Compose render props imperatively with async/await...

 5 years ago
source link: https://github.com/Astrocoders/epitath
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

epita✞h

In memoriam HOCs and Render Props

import epitath from 'epitath'
...

const App = epitath(function*() {
  const { loading, data } = yield <Query />
  const { time } = yield <Time />

  return (
    <div className="App">
      {loading ? (
        <h1>Loading</h1>
      ) : (
        <div>
          <h1>{`Hello, ${data.user.name}`}</h1>
          <h2>The time is {time.toLocaleString()}!</h2>
        </div>
      )}
    </div>
  )
})

npm package

Compose HOCs imperatively like async/await. No callback hell!

Live demo Source of demo

Install

yarn add epitath

or

npm install --save epitath

Why

Render props are amazing for providing more functionality but once you need to stack a bunch of them you get what recalls a painful callback hell.

<Query>
  {({ data }) =>
    <Mutation>
      {({ mutate, result })=>
        <Form>
        etc
        </Form>
}
    </Mutation>
}
</Query>

How

Wait, we just mentioned "callback hell". So what if we had a function that would allow us to have a kind of sugar for continuation-passing-style? Or async/await feels.

And that's exactly what epitath is, it just takes care of the callbacks for you. The whole code is this:

import React from 'react'
import immutagen from 'immutagen'

export default component => {
  const generator = immutagen(component)

  const compose = context => {
    const value = context.value
    return context.next
      ? React.cloneElement(value, null, values => compose(context.next(values)))
      : value
  }

  function Epitath(props) {
    return compose(generator(props))
  }

  Epitath.displayName = `EpitathContainer(${component.displayName || 'anonymous'})`

  return Epitath
}

How is this different from Suspense?

Suspense only allows you to evalulate a promise once. It does not allow you to trigger a re-render for a state update. And with epitath you can even use Formik, Apollo optimistic, React Powerplug and Smalldots tooling and etc!

Contributing

Steps to get it running

Install the deps

yarn install

Boot the demo

yarn start

Things missing that we would like a little help

  • Tests
  • TypeScript support

Acknowledgements

Thanks @jamiebuilds for the suggestions on how simplifying the API


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK