How to Use Fetch API in JavaScript: Simple Guide with Examples
Use the
fetch() function in JavaScript to make network requests. It returns a promise that resolves to a response object, which you can process with methods like json() to get data.Syntax
The basic syntax of fetch() is simple. You call fetch() with a URL string as the first argument. It returns a promise that resolves to a response object. You can then use methods like response.json() to extract the data.
- fetch(url, options): Makes a request to the URL.
- url: The address of the resource you want.
- options: Optional settings like method, headers, body.
- response: The result of the request.
javascript
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Example
This example fetches JSON data from a public API and logs the result. It shows how to handle the promise and parse the response.
javascript
async function getData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); console.log(data); } catch (error) { console.error('Fetch error:', error); } } getData();
Output
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
Common Pitfalls
Common mistakes when using fetch() include:
- Not checking
response.okto handle HTTP errors. - Forgetting to parse the response with
json()or other methods. - Not handling network errors with
catch. - Using
fetch()withoutawaitorthen, causing unexpected behavior.
javascript
/* Wrong way: Not checking response.ok */ fetch('https://jsonplaceholder.typicode.com/todos/999999') .then(response => response.json()) // This will try to parse even if 404 .then(data => console.log(data)) .catch(error => console.error('Error:', error)); /* Right way: Check response.ok */ fetch('https://jsonplaceholder.typicode.com/todos/999999') .then(response => { if (!response.ok) { throw new Error('HTTP error ' + response.status); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Quick Reference
Here is a quick summary of key points when using fetch():
| Concept | Description |
|---|---|
| fetch(url, options) | Starts a network request, returns a promise. |
| response.ok | True if HTTP status is 200-299. |
| response.json() | Parses response body as JSON. |
| catch() | Handles network or parsing errors. |
| async/await | Simplifies promise handling with cleaner syntax. |
Key Takeaways
Use fetch() to make network requests and handle responses with promises.
Always check response.ok to catch HTTP errors before parsing data.
Parse the response with response.json() or other methods to get usable data.
Handle errors with catch() or try/catch when using async/await.
Use async/await for cleaner and easier-to-read asynchronous code.