Use the native Fetch API to load JSON data into an HTML page

Jason Lengstorf
InstructorJason Lengstorf

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

Avoid extra dependencies and unnecessary JavaScript bloat by using the built-in Fetch API to call a Netlify Function and load JSON data into an HTML page.

Jason Lengstorf: [0:00] To load data into our pages we're going to use Vanilla JS and the Fetch API. Let's create a new folder called js. Inside of that we'll create load-products.js. This is going to be a is-module, because that's supported in most major browsers now. I'm going to export async function, and we'll call this loadProducts().

[0:28] We're going to load all of our products into a data constant, and we'll do that by using the Fetch API, with async await, so fetch, and we want to fetch that function that we created, so /.netlify/functions/get-products.

[0:47] When this comes back it's a promise, so we can .then, and we'll get the response, and we want the JSON version of that response. In case anything goes wrong, we're going to catch an error, and we will just console.error so that we know what went wrong.

[1:06] Below that we're going to grab the products = document.querySelector, and we want to grab products, and if we look at our HTML we can see that we need that. Let's create a div. We'll call it products, and that's just going to be an empty div. We'll save that, and then out here, we can add things to it.

[1:32] What we're ultimately going to want to do is add markup to display the products, but for now we're going to just dump it in a pre tag. We will document.createElement, and we'll use a pre tag for this. Then we're going to set the innerText of that to be JSON.stringify(data, null, 2). We'll do some formatting, so that it's a little easier to read.

[2:01] Then, we're going to append this to our products div. Once we've saved that, this is available to use, but we're not quite using it yet.

[2:13] The next thing we need to do is go back into our index.html and we need to add a script, and we're going to set the type to module so we can do is imports. I'm going to import { loadProducts } from './js/load-products.js' and then we can call it, loadProducts.

[2:37] I come back out here and start our server, ntl dev. It's going to open up our dev server and we can see that the products got loaded and appended to the document.