Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/thedvlprs/js-fetch-api

✨ JavaScript Fetch API example
https://github.com/thedvlprs/js-fetch-api

demo fetch-api json

Last synced: about 2 months ago
JSON representation

✨ JavaScript Fetch API example

Awesome Lists containing this project

README

        

[![forthebadge](https://forthebadge.com/images/badges/built-with-grammas-recipe.svg)](https://forthebadge.com)

#JavaScript Fetch API example

Suppose that you have a `json file` that locates on the webserver with the following contents:

```json
[{
"username": "john",
"firstName": "John",
"lastName": "Doe",
"gender": "Male",
"profileURL": "img/male.png",
"email": "[email protected]"
},
{
"username": "jane",
"firstName": "Jane",
"lastName": "Doe",
"gender": "Female",
"profileURL": "img/female.png",
"email": "[email protected]"
}
]
```

The following shows the `HTML page`:

```html



Fetch API Demo


```

In the `app.js`, we’ll use the `fetch() method` to get the user data and **render the data** inside the `

element` with the `class container`.

First, declare the `getUsers() function` that fetches `users.json` from the **server**.

```js
async function getUsers() {
let url = 'users.json';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
```

Then, develop the `renderUsers() function` that **renders user data**:

```js
async function renderUsers() {
let users = await getUsers();
let html = '';
users.forEach(user => {
let htmlSegment = `



${user.firstName} ${user.lastName}



`;

html += htmlSegment;
});

let container = document.querySelector('.container');
container.innerHTML = html;
}

renderUsers();
```

###Output

![](demo.png)