This video is available to students only

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:

  1. A user navigates to a route in a Single Page Application

  2. The component for the route needs data from the server

  3. The component shows a loading spinner icon to tell the user that something is happening

  4. The component triggers a network call to fetch the data

  5. When the data is retrieved, the loading spinner is hidden and the UI is updated with the data

There is a lot going on in the above steps, but Svelte makes it easy to dynamically update the UI with spinner icons and data. We will also use a library called Axios that makes HTTP network calls in JavaScript.

We will follow the above example steps to fetch our lunchWeekList and display the data on our frontend admin/manage-menus component.

Open up LunchMenuAdmin.svelte and start by adding a variable called lunchWeekList to the script and to the markup under the <h1 class="title is-4">:

Run 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:

hardcoded-lunch-week-list

On-Mount Initialization#

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.

Next, in LunchMenuAdmin.svelte, importonMount and update the lunchWeekList array in the onMount function:

Confirm that the onMount function updated the state correctly:

lunch-week-list-onMount

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 async or await. Network calls in JavaScript are asynchronous functions which means that JavaScript doesn't block and wait for the line of code to finish. The next line of code can execute prior to the previous line finishing.

By prefixing the call to Axios with the await keyword, the browser will wait for the async call to finish before running the next line of code.

 

This page is a preview of Fullstack Svelte

Please select a discussion on the left.