Efficiently fetching data from APIs is a fundamental task in web development, and there are multiple ways to achieve this. Let’s explore different methods for making API calls in a Svelte application.
Suppose we want to retrieve a list of tasks from a mock API and display them in our Svelte application. Let’s see how we can do this with different methods.
Let’s see how to fetch an API in the script block in the Svelte application:
import App from './App.svelte'; const app = new App({ target: document.body, }); export default app;
Variable declaration:
Line 1: let tasks = [];
declares an array to store the fetched tasks.
API call function:
Line 6: async function fetchData() { ... }
defines an asynchronous function for making the API call.
Line 9: const response = await fetch('https://jsonplaceholder.typicode.com/todos');
uses the Fetch API to get data from the mock API.
Line 12: tasks = await response.json();
parses the JSON data from the response and assigns it to the tasks
variable.
Error handling:
Lines 13–16: catch (error) { console.error('Error fetching data:', error); }
handles any errors that may occur during the API call.
Component mounting:
Line 20: import { onMount } from 'svelte';
imports the onMount
function from Svelte.
Line 21: onMount(fetchData);
calls the fetchData
function when the component is mounted.
Displaying fetched tasks:
Line 27: {#each tasks as task (task.id)}
uses Svelte’s #each
block to iterate over the tasks
array.
Line 29: <li>{task.title}</li>
displays each task’s title in a list item.
fetch
function in the markupLet’s see how to utilize the fetch
function in the markup to make an API call:
<script> // Declare a variable to store the fetched tasks let tasks = []; // Define an asynchronous function to fetch data from the API async function fetchData() { try { // Use Svelte's built-in $fetch function to make the API call const response = await fetch('https://jsonplaceholder.typicode.com/todos'); // Extract JSON data from the response const data = await response.json(); // Assign the response data directly to the 'tasks' variable tasks = data; } catch (error) { // Handle errors that may occur during the API call console.error('Error fetching data:', error); } } // Call the fetchData function when the component is mounted using the onMount lifecycle function import { onMount } from 'svelte'; onMount(fetchData); </script> <main> <h1>Svelte data fetching example with API call using the fetch function</h1> <ul> {#each tasks as task (task.id)} <!-- Iterate over each task and display its title in a list item --> <li>{task.title}</li> {/each} </ul> </main>
Variable declaration:
Line 1: let tasks = [];
declares an array to store the fetched tasks.
API call function:
Line 6: async function fetchData() { ... }
defines an asynchronous function for making the API call.
Line 9: const response = await fetch('https://jsonplaceholder.typicode.com/todos');
uses Svelte's built-in fetch
function to get data from the mock API.
Line 12: const data = await response.json();
extracts JSON data from the response
.
Line 15: tasks = data;
assigns the response data in JSON format to the tasks
variable.
Error handling:
Lines 16–19: catch (error) { console.error('Error fetching data:', error); }
handles any errors that may occur during the API call.
Component mounting:
Line 23: import { onMount } from 'svelte';
imports the onMount
function from Svelte.
Line 24: onMount(fetchData);
calls the fetchData
function when the component is mounted.
Displaying fetched tasks:
Line 30: {#each tasks as task (task.id)}
uses Svelte’s #each
block to iterate over the tasks
array.
Line 32: <li>{task.title}</li>
displays each task’s title in a list item.
Now, let's fetch data with the assistance of a Svelte store, an efficient approach to manage the state within our application.
<script> // Import the writable store from Svelte import { writable } from 'svelte/store'; // Create a writable store named 'tasks' and initialize it with an empty array const tasks = writable([]); // Define an asynchronous function to fetch data from the API async function fetchData() { try { // Make an API call using the Fetch API to the specified URL const response = await fetch('https://jsonplaceholder.typicode.com/todos'); // Parse the JSON data from the response const data = await response.json(); // Update the 'tasks' store with the fetched data tasks.set(data); } catch (error) { // Handle errors that may occur during the API call console.error('Error fetching data:', error); } } // Call the fetchData function when the component is mounted using the onMount lifecycle function import { onMount } from 'svelte'; onMount(fetchData); </script> <main> <h1>Svelte data fetching example with API call using state management</h1> <ul> {#each $tasks as task (task.id)} <!-- Iterate over each task and display its title in a list item --> <li>{task.title}</li> {/each} </ul> </main>
Store declaration:
Line 3: import { writable } from 'svelte/store';
imports the writable store from Svelte.
Line 6: const tasks = writable([]);
creates a writable store named tasks
and initializes it with an empty array.
API call function:
Line 9: async function fetchData() { ... }
defines an asynchronous function for making the API call.
Line 12: const response = await fetch('https://jsonplaceholder.typicode.com/todos');
uses the Fetch API to get data from the mock API.
Line 15: const data = await response.json();
parses the JSON data from the response.
Line 18: tasks.set(data);
updates the tasks
store with the fetched data.
Error handling:
Lines 19–22: catch (error) { console.error('Error fetching data:', error); }
handles any errors that may occur during the API call.
Component mounting:
Line 26: import { onMount } from 'svelte';
imports the onMount
function from Svelte.
Line 27: onMount(fetchData);
calls the fetchData
function when the component is mounted.
Displaying fetched tasks:
Line 33: {#each $tasks as task (task.id)}
uses Svelte’s #each
block to iterate over the tasks
store.
Line 35: <li>{task.title}</li>
displays each task’s title in a list item.
Exploring these different methods for making API calls in Svelte allows us to choose the approach that aligns most with our project requirements and development preferences. Whether we prefer working directly with the Fetch API, leveraging Svelte’s fetch
function, or adopting a store for state management, Svelte offers the flexibility to meet our application’s needs.
Free Resources