#how to fetch large data in react component and have it pre-rendered so that it is visible instantly

3 messages · Page 1 of 1 (latest)

tender sandal
#

how to fetch large data in react component and have it pre-rendered so that it is visible instantly and hydrated on load

cloud helmBOT
#

Hi @tender sandal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, you can fetch data in your React component and have it pre-rendered for instant visibility. Here's how you can do it:

  1. Fetch the data in your component. The fetch() function is globally available to any framework components. Here's an example of how you can use it in a React component:
import type { FunctionalComponent } from 'preact';

const data = await fetch('<https://example.com/movies.json'>).then((response) =>  response.json());

console.log(data);

const Movies: FunctionalComponent = () => {
  return <div>{JSON.stringify(data)}</div>;
};

export default Movies;

(Source: Astro Documentation (https://docs.astro.build/en/guides/data-fetching/#fetch-in-framework-components))

  1. To have the component pre-rendered, you can use the prerender export. For a mostly server-rendered app configured as output: server, add export const prerender = true to any page or route to pre-render a static page or endpoint:
export const prerender = true;

(Source: Astro Documentation (https://docs.astro.build/en/guides/server-side-rendering/#opting-in-to-pre-rendering-in-server-mode))

  1. To hydrate the component on load, you can use the client:load directive in Astro. This will load and hydrate the component JavaScript once the HTML has loaded:
<Movies client:load />

Please note that the above examples are for Astro, not React. Astro allows you to build websites with your favorite JavaScript framework (including React), but it isn't a React-specific tool. If you're working with React outside of Astro, the approach may be different.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: