본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

useFetch

원문 보기 위키 갱신

useFetch (데이터 불러오기)

useFetch 훅은 지정한 URL로 GET 요청을 보내고 응답 데이터, 로딩 상태, 오류, refetch와 abort 함수를 반환해요.

출처: 문서

본문

useFetch 훅은 지정한 URL로 GET 요청을 보내고 응답 데이터, 로딩 상태, 오류, refetch와 abort 함수를 반환해요.

import { Box, Button, Code, Group, LoadingOverlay, Text } from '@mantine/core';
import { useFetch } from '@mantine/hooks';

interface Item {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

function Demo() {
  const { data, loading, error, refetch, abort } = useFetch(
    'https://jsonplaceholder.typicode.com/todos/'
  );

  return (
    <Box pos="relative" maw={400} mx="auto" mt="xl" style={{ overflow: 'hidden' }}>
      <LoadingOverlay visible={loading} />
      {error && <Text c="red">{error.message}</Text>}
      <Group>
        <Button onClick={refetch}>Refetch</Button>
        <Button onClick={abort} color="red">
          Abort
        </Button>
      </Group>
      <Code block mt="md">
        {data ? JSON.stringify(data.slice(0, 3), null, 2) : 'Fetching'}
      </Code>
    </Box>
  );
}

정의 (Definition)

interface UseFetchOptions<T> extends RequestInit {
  autoInvoke?: boolean;
}

interface UseFetchReturnValue<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
  refetch: () => Promise<void>;
  abort: () => void;
}

function useFetch<T = any>(
  url: string,
  options?: UseFetchOptions<T>,
): UseFetchReturnValue<T>

Exported types

UseFetchOptions와 UseFetchReturnValue 타입은 @mantine/hooks 패키지에서 내보내져요.

import type { UseFetchOptions, UseFetchReturnValue } from '@mantine/hooks';

더 알아보기 (Learn more)