An open API service indexing awesome lists of open source software.

https://github.com/pie6k/suspensify

Easy way to convert any async function to suspended function
https://github.com/pie6k/suspensify

async react suspense

Last synced: 3 months ago
JSON representation

Easy way to convert any async function to suspended function

Awesome Lists containing this project

README

        

# Suspensify

Easy way to convert any async function to suspended function

```
yarn add suspensify
```

Demo: https://pie6k.github.io/suspensify/

```ts
import React, { Suspense } from 'react';
import { render } from 'react-dom';
import { suspensify } from 'suspensify';

// first - let's say we have some regular, async function
function getHelloWithDelay(name: string, delay: number) {
// just a promise that returns a string after some delay
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Hello, ${name}`);
}, delay);
});
}

// now we convert it to suspended function
const [getSuspendedHello] = suspensify(getHelloWithDelay);

// now we can just use it inside any component like it is sync function

// let's create some simple component
interface DelayedHelloProps {
delay: number;
name: string;
}

function DelayedHello({ delay, name }: DelayedHelloProps) {
const helloString = getSuspendedHello(name, delay);
return

{helloString}
;
}

// last step is to create suspense loading fallback
function App() {
return (
Loading...}>


);
}

// and start the app
render(, document.getElementById('app'));
```