https://github.com/zackify/react-suspendable
a function that can wrap any async action and make it compatible with suspense
https://github.com/zackify/react-suspendable
Last synced: about 2 months ago
JSON representation
a function that can wrap any async action and make it compatible with suspense
- Host: GitHub
- URL: https://github.com/zackify/react-suspendable
- Owner: zackify
- License: mit
- Created: 2019-11-01T20:14:31.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T23:56:06.000Z (about 3 years ago)
- Last Synced: 2025-04-07T20:14:46.661Z (11 months ago)
- Language: TypeScript
- Size: 959 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 30
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Suspender
Not really meant for anything serious yet, and may never be.
This is a package that wraps async functions to be used with Suspense. You can see in the example folder how that looks.
### Run the example
The example contains code that helped me get more familiar with suspense data loading. Take a look at the example/src directory.
```
yarn
yarn start
// in another tab
cd example
yarn
yarn start
```
## Basic fetch
```js
import { suspender } from 'react-suspender';
const getData = async type => {
if (type === 'success') {
let response = await fetch('https://test.com');
let json = await response.json();
return json;
}
};
const initialRequest = suspender(getData, 'success');
const App = () => {
let [user, setUser] = React.useState(initialRequest);
return (
sidebar loader...}>
);
};
const SomeComponent = ({ user }) => {
let { data, args } = user.read();
//args are what was passed in to the suspender / async function as the second argument
// data is the resulting promise result
return null;
};
```
## Error Handling
See `examples/src/TestContent.tsx`. You can wrap your component in an error boundary, and then you will be able to render something if an async request throws a promise rejection
## TypeScript example
```js
type User = { name: string };
// initial request must be created outside the render, or else you will be in an infinite loop
const initialRequest = suspender < User > (getData, 'success');
const App = () => {
let [user, setUser] = React.useState(initialRequest);
return (
sidebar loader...}>
);
};
// Example using TS types with suspense
type SidebarProps = {
user: Suspender,
};
const Sidebar = ({ user }: SidebarProps) => {
const { data } = user.read();
// data is correctly typed using the User type above
return null;
};
```