Git Product home page Git Product logo

suspend-react's Introduction

Build Size Version




npm install suspend-react

This library integrates your async ops into React suspense. Error-handling & loading states are handled at the parental level. The individual component functions similar to async/await in Javascript.

  • Chain your operations synchronously
  • No useEffect/setState hassle
  • No checking for the presence of your data
  • All React versions >= 16.6
import { Suspense } from 'react'
import { suspend } from 'suspend-react'

function Post({ id, version }) {
  const data = suspend(async (/*id, version*/) => {
    const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
    return await res.json()
  }, [id, version])
  return <div>{data.title} by {data.by}</div>
}

function App() {
  return (
    <Suspense fallback={<div>loading...</div>}>
      <Post id={1000} version="v0" />
    </Suspense>
  )
}

API

const result = suspend((...keys) => Promise<any>, keys: any[], config)

When you call suspend it yields control back to React and the render-phase is aborted. It will resume once your promise resolves. For this to work you need to wrap it into a <React.Suspense> boundary, which requires you to set a fallback (which can be null).

The dependencies/keys act as cache-keys, use as many as you want. If an entry is already in cache, calling suspend with the same keys will return it immediately, without breaking the render-phasse. Cache access is similar to useMemo but across the component tree. The first-arg function has to return a thenable (async function or a promise), it receives the keys as arguments. suspend will return the resolved value, not a promise! This is guaranteed, you do not have to check for validity. Errors will bubble up to the nearest error-boundary.

Both suspend and preload can optionally reveive a config object that, for now, only contains a lifespan prop that defaults to 0 (keep-alive forever). This allows you to invalidate items over time.

// Keep cached item alive for one minute
suspend(fn, keys, { lifespan: 60000 })

Preloading

import { preload } from 'suspend-react'

async function fetchFromHN(id, version) {
  const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
  return await res.json()
}

preload(fetchFromHN, [1000, 'v0'])

Cache busting

import { clear } from 'suspend-react'

// Clear all cached entries
clear()
// Clear a specific entry
clear([1000, 'v0'])

Peeking into entries outside of suspense

import { peek } from 'suspend-react'

// This will either return the value (without suspense!) or undefined
peek([1000, 'v0'])

Typescript

Correct types will be inferred automatically.

React 18

Suspense, as is, has been a stable part of React since 16.6, but React will likely add some interesting caching and cache busting APIs that could allow you to define cache boundaries declaratively. Expect these to be work for suspend-react once they come out.

Demos

Fetching posts from hacker-news: codesandbox

Infinite list: codesandbox

suspend-react's People

Contributors

codyjasonbennett avatar drcmda avatar gsimone avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.