Skip to content

JavaScript:Fetch

Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다. XMLHttpRequest와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능합니다.

POST Example

const obj = {
  body: ...,
  headers: {},
  method: 'POST'
}
fetch(URL, obj)
.then(res => res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));

Fetch 를 Abort 가능하도록

useEffect(() => {
  const controller = new AbortController();
  const signal = controller.signal;

  fetch(`/api/users/${id}`, {signal})
    .then(res => res.json())
    .then(data => {
      setUser(data);
    });

  return () => {
    controller.abort();
  };
}, [id])

Timeout

async function fetchWithTimeout(resource, options = {}) {
  const { timeout = 8000 } = options;

  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);

  const response = await fetch(resource, {
    ...options,
    signal: controller.signal  
  });
  clearTimeout(id);

  return response;
}

// ...

async function loadGames() {
  try {
    const response = await fetchWithTimeout('/games', {
      timeout: 6000
    });
    const games = await response.json();
    return games;
  } catch (error) {
    // Timeouts if the request takes
    // longer than 6 seconds
    console.log(error.name === 'AbortError');
  }
}

See also

Favorite site