Front-end 개발/JAVASCRIPT

react-query 목록 호출 (GET) 및 재 호출 테스트

별의 노트 2023. 1. 11. 14:31
반응형

react-query 목록 호출 (GET) 및 재 호출 테스트

(참고한 페이지 :https://tanstack.com/query/v4/docs/react/examples/react/pagination)

 

import styles from './styles.module.scss';
import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
importaxiosfrom 'axios';

export default function Study() {
  const [imageNumber, setImageNumber] = useState<number>(1);
  async function getCategorys(imageNumber = 0) {
    const { data } = awaitaxios.get(
      `https://dummyjson.com/products/${imageNumber}`,
    );
    return data;
  }
  const {
    data: dataCategory,
    isLoading: categoryLoading,
    isError: categoryError,
  } = useQuery({
    queryKey: ['category', imageNumber],
    queryFn: () => getCategorys(imageNumber),
  });
  if (categoryLoading) {
    return <p>로딩중</p>;
  }
  if (categoryError) {
    return <p>에러 발생</p>;
  }
console.log(dataCategory, imageNumber);
  function changeData() {
    setImageNumber(Math.floor(Math.random() * 10 + 1));
  }
  return (
    <div className={styles.study}>
      <div>
        <button onClick={changeData}>변경</button>
        {dataCategory.images.map((image, index) => {
          return (
            <p key={index}>
              <img key={index} src={image} />
            </p>
          );
        })}
      </div>
    </div>
  );
}