#data fetch in component vs. script
3 messages · Page 1 of 1 (latest)
Hi @magic glacier. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro uses a code fence (---) to identify the component script in your Astro component. This is where you can write any JavaScript code that you need to render your template, including fetching content from an API or database. The code fence is designed to guarantee that the JavaScript that you write in it is “fenced in.” It won’t escape into your frontend application, or fall into your user’s hands. This is why your fetch calls work when they are placed directly in the Astro component.
However, when you move your fetch code into a separate script file and then import it into your Astro component, it's important to note that Astro will not process your script tags in some situations. In particular, adding type="module" or any attribute other than src to a <script> tag will cause Astro to treat the tag as if it had an is:inline directive. This means that the script will be rendered into the HTML exactly as written, and local imports are not resolved and will not work. This could be why your fetch calls are not working when placed in a separate script file.
If you need to fetch data multiple times client-side, you can use a framework component (https://docs.astro.build/en/guides/framework-components/) or a client-side script (https://docs.astro.build/en/guides/client-side-scripts/) in an Astro component.
For more information, you can refer to the following documentation:
- The Component Script (https://docs.astro.build/en/basics/astro-components/#the-component-script)
- Opting out of processing (https://docs.astro.build/en/guides/client-side-scripts/#opting-out-of-processing)
- Data Fetching in Astro (https://docs.astro.build/en/guides/data-fetching/)