Skip to content

Instantly share code, notes, and snippets.

@osamaAbdullah
Created December 5, 2022 19:21
Show Gist options
  • Save osamaAbdullah/0d90382d74479adb995e7c662cc042ae to your computer and use it in GitHub Desktop.
Save osamaAbdullah/0d90382d74479adb995e7c662cc042ae to your computer and use it in GitHub Desktop.
suspense with async data fetching
import { Suspense } from 'react';
export default function Test() {
return (
<Suspense fallback={<h1>Loading...</h1>}>
<Shows />
</Suspense>
);
}
function fetchUsers() {
return new Promise((resolve) => {
setTimeout(() => {
resolve([{
id: 123,
name: 'Ringo Starr',
}, {
id: 124,
name: 'Osama Starr',
}]);
}, 500);
});
}
function osama() {
let status = 'pending';
let result;
let suspender = fetchUsers().then(
(r) => {
status = "success";
result = r;
},
(e) => {
status = "error";
result = e;
}
);
return {
read() {
if (status === 'pending') {
throw suspender;
} else if (status === 'error') {
throw result;
} else if (status === 'success') {
return result;
}
},
};
}
const resource = osama();
const Shows = () => {
resource.read();
return (
<div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment