Promises
Streaming various types of data using Promises
This example was originally created as one of several examples I wrote for a post about streaming data with promises. See that post for a more detailed explanation of the concepts here.
This example shows how we can stream various types of data to the client using Promises. Shown here are:
- strings
- integers/floats
- plain JSON objects
- arrays
- rendered React Components
This example is slightly more advanced in that it has a custom <SuspenseWrapper />
component to avoid repeated code - take a look at the other Promise-based examples if this is confusing. Basically it's still just <Suspense>
boundaries wrapping client components, passing in a Promise each time. The getData
function just makes it easy for the example to return different types of data.
Explanation
The example uses its getData
function to simulate the fetching of different types of data with different delays. <SuspenseWrapper>
is a trivial custom component that wraps <ClientPromise>
in a <Suspense>
boundary, passing in the Promise returned by getData
. It's important to keep those <Suspense>
boundaries in the server component templates, not in client components.
ClientPromise
is a trivial client-side component that just renders the contents of a resolved Promise into a <div>
or <pre>
tag, depending on the type of the resolved value. We render a red border around it in the example to make it clear where the client component is.
The final example shows us returning a rendered React Component (or Component tree) from a Promise. This is a powerful feature of React Server Components, as it allows us to return complex client-side components from server components. In this case, we're just returning a simple <ServerChildComponent>
with some data.
This one is just a <ClientPortal>
wrapped in a <Suspense>
boundary. ClientPortal is a trivial client component that expects a childrenPromise
prop, which is a Promise that resolves to a ReactNode. It uses the use
hook to get the resolved value and render it, wrapping it in a blue border this time to show it's inside a client component.
The Portal component here is purely to show that a React component can be returned from a Promise and rendered on the client, which may be helpful in some cases, but <Suspense>
already handles this for you in most cases:
Live Demo
This example can't be easily inlined as it demonstrates how a full-page feels to the end user. Here it is inside an iframe, and there's a looping video below too.
Video Preview
In case the iframe doesn't work for some reason, this is a looping video of what you would see. Click the video to open the full page example in a new tab.