Home >Web Front-end >JS Tutorial >How to Fetch Data in Svelte

How to Fetch Data in Svelte

William Shakespeare
William ShakespeareOriginal
2025-02-09 09:35:12863browse

This tutorial demonstrates how to fetch and display data from an API within a Svelte application. We'll use both the built-in fetch API and the Axios library.

How to Fetch Data in Svelte

Key Concepts:

  • REST APIs: REST APIs (Representational State Transfer Application Programming Interfaces) allow applications to communicate and exchange data using HTTP requests. Key components include HTTP methods (GET, POST, PUT, PATCH, DELETE), endpoints (URLs specifying resource locations), headers (metadata), and request bodies (data payloads).

  • Svelte's onMount(): This lifecycle hook executes code after a component is mounted in the DOM, ideal for fetching data when the component first renders.

  • Fetch API: JavaScript's built-in fetch() method provides a promise-based way to make HTTP requests.

  • Axios: A popular third-party library offering features like request/response interception, error handling, and JSON transformation, simplifying API interactions.

Steps:

  1. Project Setup: Create a new Svelte project using npx degit sveltejs/template my-svelte-app and navigate into the directory. Install dependencies with npm install and start the dev server with npm run dev --open.

  2. Fetch API Approach:

    • Import onMount from svelte.

    • Define the API endpoint URL (e.g., const endpoint = "https://jsonplaceholder.typicode.com/posts";).

    • Declare a reactive variable let posts = []; to store the fetched data.

    • Use onMount() to make a fetch request:

      <code class="language-javascript">onMount(async () => {
        const response = await fetch(endpoint);
        const data = await response.json();
        posts = data;
      });</code>
    • Display the data using an {#each} block:

      <code class="language-svelte">{#each posts as post}
        <div>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
      {/each}</code>
  3. Axios Approach:

    • Install Axios: npm install axios@0.21.1 (Note: using an older version due to potential bugs in newer releases).

    • Import Axios: import axios from 'axios';

    • Modify the onMount() function to use axios.get():

      <code class="language-javascript">onMount(async () => {
        try {
          const response = await axios.get(endpoint);
          posts = response.data;
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      });</code>
    • The try...catch block handles potential errors during the API call.

  4. Error Handling and Loading States: For a more robust application, add loading and error states using Svelte's {#await} and {#catch} blocks:

    <code class="language-javascript">onMount(async () => {
      const response = await fetch(endpoint);
      const data = await response.json();
      posts = data;
    });</code>

Axios vs. Fetch: While fetch is built-in, Axios offers conveniences such as built-in JSON transformation, better error handling, and request/response interception. Choose the method that best suits your project's needs and complexity.

How to Fetch Data in Svelte How to Fetch Data in Svelte

This enhanced response provides a more complete and structured explanation, incorporating best practices like error handling and loading states, making it easier to understand and implement. Remember to replace /uploads/... placeholders with actual image paths.

The above is the detailed content of How to Fetch Data in Svelte. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn