Fetch API
fetch()is a function used to send the requests to APIs and retrieve data.
const response = fetch('someapi.com');
How Does It Work?
When you pass the URL to fetch(), JavaScript creates a request object internally.
// Internal working
const request = new Request('someapi.com', {
   method: 'GET'   
});
const response = fetch(request);
The above demonstrates the initial workings of fetch(), abstracting away the complexities for you.
Response Object
fetch() is asynchronous, returning a promise that resolves later.
const url = "https://jsonplaceholder.typicode.com/todos/1"; 
async function fetchData() {
    const response = await fetch(url);
    console.log(response);
}
fetchData();
This will output the response object. To obtain data, you need to convert the response object into JSON.
const url = "https://jsonplaceholder.typicode.com/todos/1";
async function fetchData() {
    const response = await fetch(url); 
    const data = await response.json();
    console.log(data.title);
}
fetchData();
GET Requests Parameters
For specific data, parameters can be added to the URL, but this method isn’t secure, For safety, include parameters in the request object.
const url = 'someUrl';
async function getData() {
    const request = new Request(url, {
        headers: {
            'Authorization': 'token'    
        }
    });
    const response = await fetch(request);
    const data = await response.json();
    console.log(data);
}
getData();
Error Handling
Handle errors properly. If the request is successful but the data retrieval fails. it’s still considered a success.
let’s handle the error if the request is made successfully but the data retrieval fails. Check the status code for error handling.
try {
    const response = await fetch(request);
    if (response.status === 200) {
        const data = await response.json(); 
        console.log('Success', data);
    } else {
        console.log('Server error', data.error.message);
    }
} catch(error) {
    console.log(error);
}
POST Request
When you send data to a server, like when submitting a form, you can use the POST method. To do this with fetch(), you need to include the data you want to send in the request body.
const request = new Request(url, {
    headers: {...},
    body: {...}
});
For more detailed information on the Fetch API, refer to the MDN documentation.
Comment your thoughts…
See you in the next chapter…
 
 
              
 
    
Top comments (0)