🚀How to fetch API in Proper way & Add additional features 🌟
Tags: webdev, javascript, programming, api
Published: 2023-07-26 13:30:23

🚀 Many individuals are facing the challenge of optimizing API calls to reduce their frequency. They may be unsure of the proper approach for fetching APIs and minimizing the number of calls, while incorporating additional features during data retrieval.

**Outlined below is a code snippet that illustrates the appropriate and efficient way to achieve this:**

```
// 🌐 API Endpoint
const apiURL = 'https://jsonplaceholder.typicode.com/photos';

// 🔄 Fetch and Cache Data Function
const fetchDataAndCache = async () => {
  try {
    const startTime = performance.now();

    // 📦 Check if data exists in cache
    const cachedData = sessionStorage.getItem('cachedData');
    if (cachedData) {
      const dataFromCache = JSON.parse(cachedData);
      const dataSizeInKB = JSON.stringify(dataFromCache).length / 1024;
      console.log('🗃️ Data Loaded from Cache - Size:', dataSizeInKB.toFixed(2), 'KB');
      processData(dataFromCache, 'cache');
    } else {
      // 🌐 Fetch data from API if not in cache
      const response = await fetch(apiURL);
      if (!response.ok) {
        throw new Error('❌ Network response was not ok.');
      }
      const dataFromAPI = await response.json();
      sessionStorage.setItem('cachedData', JSON.stringify(dataFromAPI));
      const dataSizeInKB = JSON.stringify(dataFromAPI).length / 1024;
      console.log('🌐 Data Loaded from API - Size:', dataSizeInKB.toFixed(2), 'KB');
      processData(dataFromAPI, 'api');
    }

    const endTime = performance.now();
    console.log('⏱️ Fetch API Time:', endTime - startTime, 'ms');

    let fetchCount = parseInt(sessionStorage.getItem('fetchCount')) || 0;
    fetchCount++;
    sessionStorage.setItem('fetchCount', fetchCount);
    console.log('🔢 Fetch Count:', fetchCount);
  } catch (error) {
    console.error('❗ Fetch API Error:', error.message);
    console.log('💡 Explanation: The Cross-Origin Resource Sharing (CORS) policy is enforced by the server to protect against unauthorized access from different domains. If you are the API owner, ensure proper CORS header configuration to permit access from your domain.');
  }
};

// 🔄 Process Data Function
const processData = (data, source) => {
  console.log('🔍 Sample Data:', data.slice(0, 5));
  console.log('📄 Full Data:', data);
  console.log('📍 Data Loaded from:', source);
};

// 🚀 Fetch and Cache Data on Script Load
fetchDataAndCache();
```

## Here is the Output of the code:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iceiw25i1ki2osojy53k.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4zrdj6mx9aid93ymeyj.png)

👍 If you find this content helpful, we encourage you to like and share it with your friends, so they can also benefit from these API fetching techniques.

Furthermore, should you require web development services, feel free to consider my expertise. You can connect with me on LinkedIn and explore my Upwork and Dev.to profiles:

Upwork Profile: [Upwork Profile](https://www.upwork.com/freelancers/~013e2126c3a07fbd7d)

LinkedIn Profile: [Linkedin Profile](https://www.linkedin.com/in/bhavya-j-shah/)

Dev.to Profile: [Dev.to Profile](https://dev.to/bhavyashah)

Thank you for your time and consideration. Should you have any inquiries or require further assistance, please do not hesitate to reach out. 🙏