React Server Component with External API Integration
Display a use-case of a React Server Component fetching data from an external API, rendering the response on the server side before sending it to the client.
import { createFromFetch } from 'react-server-dom-webpack';
// This is your server component which uses fetch to load data from an API
export default function ServerComponent() {
// Use createFromFetch to create a resource from a fetch call
const resource = createFromFetch(fetch('https://api.example.com/data'));
// The resource is read in the render, this will
// throw a promise if the resource is not yet ready
// and suspend rendering
const data = resource.read();
return (
<div>
<h1>Data from API</h1>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
This piece of code demonstrates how to create a React server component that fetches data from an external API using createFromFetch to create a data-fetching resource. This resource is then read during rendering. If the data isn't ready, it will throw a promise to suspend the rendering, and once the data is ready, it will display it inside a div element.