import { useQuery } from 'react-query';
unique key (super-heroes) μ promise(return axios.get) λ₯Ό 리ν΄νλ ν¨μλ₯Ό μΈμλ‘ λ°λλ€.
ex) ν¨μλ json server λ‘λΆν° get request λ₯Ό νλ€.
const results = useQuery('super-heroes', () => {
return axios.get('http://localhost:5000/superheroes');
});
results λ νμ¬ query μμ λ΄κ° νμλ‘ν λͺ¨λ κ²μ΄ λ΄κ²¨μλ€.
result => { isLoading, data }
const results = useQuery('super-heroes', () => {
return axios.get('http://localhost:5000/superheroes');
});
const { isLoading, data } = useQuery('super-heroes', () => {
return axios.get('http://localhost:5000/superheroes');
});
optional chaining μΌλ‘ data κ° μμ΄λ μλ¬κ° λμ§ μκ²νκΈ°
return (
<>
<h2>React Query Super Heroes Page</h2>
{data?.data.map((hero) => {
return <div key={hero.name}>{hero.name}</div>;
})}
</>
);
useQuery μ λλ²μ§Έ μΈμμ inline μΌλ‘ data fetching ν¨μλ₯Ό λ£μ§ μκ³ λ°μμ μ μΈνλ κ²(fetchSuperHeroes)μ΄ react query μ μΌλ°μ μΈ pattern
const fetchSuperHeroes = () => {
return axios.get('http://localhost:5000/superheroes');
};
const { isLoading, data } = useQuery('super-heroes', fetchSuperHeroes);
import { useQuery } from 'react-query'; // import data fetching Hook
import axios from 'axios';
export const RQSuperHeroesPage = () => {
// Hook λΆλ¬μ€κΈ° // 1. (unique key) μ 2. (promise λ₯Ό 리ν΄νλ ν¨μ)λ₯Ό μΈμλ‘ λ°λλ€.
// ex) ν¨μλ json server λ‘λΆν° get request λ₯Ό νλ€.
// query hook μ ν΅ν΄μ 리ν΄λ query result λ₯Ό μ¬μ©νλ€.
// results λ νμ¬ query μμ λ΄κ° νμλ‘ν λͺ¨λ κ²μ΄ λ΄κ²¨μλ€.
// results μμμ λ΄κ° νμν μμλ§ destructuring νλ€. result => { isLoading, ..}
// useQuery μ λλ²μ§Έ μΈμμ inline μΌλ‘ data fetching ν¨μλ₯Ό λ£μ§ μκ³
// λ°μμ μ μΈνλ κ²(fetchSuperHeroes)μ΄ react query μ μΌλ°μ μΈ pattern
const fetchSuperHeroes = () => {
return axios.get('http://localhost:5000/superheroes');
};
const { isLoading, data } = useQuery('super-heroes', fetchSuperHeroes);
// λΆλ¬μ¨ κ°λ€μ νμ©ν΄μ jsx λ λλ§ νκΈ°
if (isLoading) {
return <h2>Loading...</h2>;
}
// optional chaining "?" νμ©ν΄μ data κ° μλλΌλ μλ¬κ° λμ§ μκ² μ²λ¦¬νλ€.
return (
<>
<h2>React Query Super Heroes Page</h2>
{data?.data.map((hero) => {
return <div key={hero.name}>{hero.name}</div>;
})}
</>
);
};
React Query Tutorial μ°Έκ³ νλ©° 곡λΆν λ΄μ©μ λλ€.