Front-end/Next.js

JSON API 데이터 사용하기 (JSONPlaceholder)

Bay Im 2024. 3. 8. 00:32

JSON API 데이터 사용하기 (JSONPlaceholder)

  • 기본 URL 변수 생성
  • 가져올 데이터의 json 형식에 맞추어 type생성
  • type Photo = {
      albumId: number;
      id: number;
      title: string;
      url: string;
      thumnailUrl: string;
    };
  • 데이터를 넣을 변수와 setter 생성 (useState 사용)
    • const [photos, setPhotos] = useState<Photo[]>([]);
  • 데이터 가져오는 함수 생성
    • function에 async 넣기
    • fetch() 사용하여 데이터를 가져올 url 작성 후, fetch 앞에 await 작성하여 변수 생성
    • 데이터를 넣을 변수는 위에서 만든 type (Photo[]) 으로 주고, 값은 fetch 사용하여 만든 변수 뒤에 .json() 을 붙인다. 이것도 앞에 await 붙이기.
    • 위에서 생성한 setter에 데이터 넣어주기
    const fetchData = async () => {
      const photoResponse = await fetch(
        `${BASE_URL}/photos?albumId=${albumId}`
      );
      const photoData: Photo[] = await photoResponse.json();
      setPhotos(photoData);
    };
    
  • 함수 추가 기능
    • try-catch 사용
      • 위에서 만든 fetchData에 try-catch 문을 사용하여 에러 발생 시 빈 값으로 set
    const fetchData = async () => {
      **try** {
        const photoResponse = await fetch(
          `${BASE_URL}/photos?albumId=${albumId}`
        );
        const data: Photo[] = await photoResponse.json();
        setPhotos(data);
      } **catch** (error) {
        console.error(error);
        setPhotos([]);
      }
    };
    
    • useEffect() 사용
    **useEffect**(() => {
      const fetchData = async () => {
        try {
          const photoResponse = await fetch(
            `${BASE_URL}/photos?albumId=${albumId}`
          );
          const data: Photo[] = await photoResponse.json();
          setPhotos(data);
        } catch (error) {
          console.error(error);
          setPhotos([]);
        }
      };
    
      if (albumId) {
        fetchData();
      }
    }, [albumId]);
    
  • 데이터 출력하기
    • setter로 넣은 photos에 map 을 사용하여 데이터 출력
    <div className='flex flex-wrap p-4'>
      **{photos.map((photo) => (
        <div key={photo.id} className='w-1/4 p-2'>
          <img
            src={photo.thumbnailUrl}
            alt={photo.title}
            className='w-40 h-40 object-cover'
          />
        </div>
      ))}**
    </div>