Fetching Data with Axios
Fetching Data from the Frontend with Axios
Fetching Data in Web Apps#
In this lesson, we are going to learn how to use our frontend Svelte application to fetch data from our backend Express endpoints. The following is a common use case in web applications:
A user navigates to a route in a Single Page Application
The component for the route needs data from the server
The component shows a loading spinner icon to tell the user that something is happening
The component triggers a network call to fetch the data
When the data is retrieved, the loading spinner is hidden and the UI is updated with the data
We will follow the above example steps to fetch our
lunchWeekList and display the data on our frontend
LunchMenuAdmin.svelte and start by adding a variable called
lunchWeekList to the script and to the markup under the
<h1 class="title is-4">:
npm run start and get the front end started, then bring up the manage-menus route.
As a reminder, the frontend dev server runs on port 5000. Here's the link to the manage-menus route we used before http://localhost:5000/admin/manage-menus.
You should see the
lunchWeekList rendered on the DOM:
In the Front End Routing module, we discussed the Svelte
onMount lifecycle function.
onMount is a good place to set up component initialization code, such as fetching data from a server.
onMount and update the
lunchWeekList array in the
Confirm that the
onMount function updated the state correctly:
Cool. We have the
onMount function working successfully.
Using Axios to Fetch Data#
Axios gives us an easy syntax to fetch data from APIs:
While the above syntax looks pretty straightforward, there is some complexity lurking under the covers. An important concept in the above code is the usage of