Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/thedvlprs/js-fetch-api
- Owner: thedvlprs
- Created: 2020-11-21T15:05:29.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2020-11-21T15:08:02.000Z (about 4 years ago)
- Last Synced: 2024-02-09T05:22:51.987Z (12 months ago)
- Topics: demo, fetch-api, json
- Language: JavaScript
- Homepage: https://tasteless-rule.surge.sh/
- Size: 117 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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 = `html += htmlSegment;
});let container = document.querySelector('.container');
container.innerHTML = html;
}renderUsers();
```###Output
![](demo.png)