8MenengahPertemuan ke-8

API & HTTP Requests

Fetch data dari API menggunakan fetch atau axios, handle loading/error states.

Topik Pembelajaran

  • Fetch API basics
  • Axios library
  • GET, POST, PUT, DELETE requests
  • Error handling
  • Loading states
  • Response interceptors
  • API best practices

Referensi & Sumber Daya

API & HTTP Requests

Fetch API

Native JavaScript API untuk HTTP requests.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Axios Library

Promise-based HTTP client dengan features lebih.

import axios from 'axios';

axios.get('/api/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

HTTP Methods

  • GET: Fetch data
  • POST: Create data
  • PUT/PATCH: Update data
  • DELETE: Remove data
  • Error Handling

    Handle network errors, timeouts, dan error responses.

    try {
      const response = await axios.get('/api/data');
    } catch (error) {
      if (error.response) {
        // Server responded with error status
        console.error(error.response.status);
      } else if (error.request) {
        // Request made but no response
        console.error('No response');
      }
    }

    Loading States

    Manage UI state saat loading, error, dan success.

    Request/Response Interceptors

    Global handling untuk requests dan responses.