Created
December 5, 2022 19:21
-
-
Save osamaAbdullah/0d90382d74479adb995e7c662cc042ae to your computer and use it in GitHub Desktop.
suspense with async data fetching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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