Separating API Functionality
Learning objectives
- You know how to extract API-related functionality to separate files.
In the previous part, the component that was used to retrieve and display the nameday using the Nameday API was as follows.
<script>
let nameday = $state("");
const day = $state(1);
const month = $state(1);
const fetchNameDay = async () => {
const data = {
day: day,
month: month,
country: "fi",
};
const response = await fetch("https://nameday.abalin.net/api/V1/getdate", {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
});
const jsonData = await response.json();
nameday = jsonData.nameday.fi;
};
</script>
<button on:click={fetchNameDay}>Fetch nameday</button>
<p>Nameday: {nameday}</p>
When we consider the above component, we can observe that the functionality for calling the API creates a bit of clutter. To make the component easier to read, it would be meaningful to separate the API functionality from the component.
To do so, let's create a separate folder called http-actions
to the src
folder. In the folder, create a new file called nameday-api.js
and place the following content to the file. The function fetchFinnishNameDay
is a variant of the function in the above component. However, instead of updating the nameday
variable, it returns the nameday as a string, and takes the name and month as parameters.
const fetchFinnishNameDay = async (day, month) => {
const data = {
day,
month,
country: "fi"
};
const response = await fetch("https://nameday.abalin.net/api/V1/getdate", {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
});
const jsonData = await response.json();
return jsonData.nameday.fi;
};
export { fetchFinnishNameDay };
Now, to use the above function in our component, we need to import it. Further, we need to adjust the old fetchNameDay
function to use the imported function. As a whole, this would look as follows.
<script>
import { fetchFinnishNameDay } from "../http-actions/nameday-api.js";
let nameday = $state("");
const day = $state(1);
const month = $state(1);
const fetchNameDay = async () => {
nameday = await fetchFinnishNameDay(day, month);
};
</script>
<button on:click={fetchNameDay}>Fetch nameday</button>
<p>Nameday: {nameday}</p>
Now, the component would be easier to read, as the API functionality is separated from the component. Further, the API functionality could be reused in other components as well.