Last active
January 23, 2024 17:36
-
-
Save growupanand/9ed9796eff511e74cbf9bd8f91761e1d to your computer and use it in GitHub Desktop.
Snippet of React Suspense component, which can be used to show fallback UI while a component loading data
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 const fakeTimeout = (ms) => { | |
return new Promise((resolve) => setTimeout(resolve, ms)); | |
}; | |
const wrapPromise = (promise) => { | |
let status = "pending"; | |
let result = ""; | |
let suspender = promise.then( | |
(res) => { | |
status = "success"; | |
result = res; | |
}, | |
(err) => { | |
status = "error"; | |
result = err; | |
} | |
); | |
return { | |
read() { | |
if (status === "pending") { | |
throw suspender; | |
} else if (status === "error") { | |
throw result; | |
} else if (status === "success") { | |
return result; | |
} | |
}, | |
}; | |
}; | |
const getUser = async () => { | |
await fakeTimeout(3000); | |
return { | |
name: "Utkarsh Anand", | |
}; | |
}; | |
const fetchUser = wrapPromise(getUser()); | |
const User = () => { | |
const user = fetchUser.read(); | |
return <div>name - {user.name}</div>; | |
}; | |
export default function App() { | |
return ( | |
<div className="App"> | |
<h3>React Suspense</h3> | |
<Suspense fallback={<p>loading component</p>}> | |
<User /> | |
</Suspense> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment