Introduction
In JavaScript, fetch() is used to request data from APIs. The data is usually returned in JSON format, which must be converted into a JavaScript object to be usable.
How Fetch Works
- A request is sent to the API using
fetch(). - A response is received from the server.
- The response data (JSON) is converted into a JavaScript object.
- The data is accessed and used in the application.
Basic Example
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data));
Understanding API Data
Example JSON response:
[
{
"id": 1,
"name": "Leanne Graham",
"email": "leanne@gmail.com"
}
]
After conversion, the data can be accessed as a JavaScript object:
console.log(data[0].name);
console.log(data[0].email);
Accessing Specific Values
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
console.log(data[0].name);
console.log(data[1].email);
});
Looping Through Data
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
data.forEach(user => {
console.log(user.name);
});
});
Using Async/Await
async function getUsers() {
let response = await fetch("https://jsonplaceholder.typicode.com/users");
let data = await response.json();
console.log(data);
}
getUsers();
Formatting Data for Readability
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
data.forEach(user => {
console.log("Name: " + user.name);
console.log("Email: " + user.email);
});
});
Working with API Data
When data is received from an API, it is in JSON format. After using response.json(), it becomes a JavaScript object.
You can then:
- Access values using
data.property - Access array elements using
data[index] - Access nested data using
data[index].property.subproperty
Example:
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
console.log(data[0].address.city);
});
You can also transform or filter the data:
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
let names = data.map(user => user.name);
console.log(names);
});
Common Mistake
Incorrect:
fetch(url).then(response => console.log(response));
Correct:
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
To work with API data in JavaScript:
- Use
fetch()to request data - Convert the response using
response.json() - Access and format the data as needed
This process allows you to transform raw API data into a readable and usable format.
Top comments (0)