주로 Input을 관리할 때, Fetch를 요청할 때 사용한다.
useFetch 사용 전
//App.js
import { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [quote, setQuote] = useState(null);
const [loading, setLoading] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setLoading('loading...')
setQuote(null);
setError(null);
const source = axios.CancelToken.source();
axios.get('https://api.quotable.io/random', { cancelToken: source.token })
.then(res => {
setLoading(false);
setQuote(res.data.content);
})
.catch(err => {
setLoading(false)
setError('An error occurred. Awkward..')
})
return () => {
source.cancel();
}
}, [])
return (
<div className="App">
<button onClick={fetchQuote}>Fetch Quote</button>
{ loading && <p>{loading}</p> }
{ quote && <p>"{quote}"</p> }
{ error && <p>{error}</p> }
</div>
)
}
export default App;
useFetch 사용 후
//useFetch.js
import { useState, useEffect } from 'react';
import axios from 'axios';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setLoading('loading...')
setData(null);
setError(null);
const source = axios.CancelToken.source();
axios.get(url, { cancelToken: source.token })
.then(res => {
setLoading(false);
res.data.content && setData(res.data.content);
res.content && setData(res.content);
})
.catch(err => {
setLoading(false)
setError('An error occurred. Awkward..')
})
return () => {
source.cancel();
}
}, [url])
return { data, loading, error }
export default useFetch;
useFetch라는 커스텀 훅을 사용했다.
컴포넌트에 useFetch 사용
import useFetch from './useFetch';
import './App.css';
function App() {
const { data: quote, loading, error } = useFetch('https://api.quotable.io/random')
return (
<div className="App">
{ loading && <p>{loading}</p> }
{ quote && <p>"{quote}"</p> }
{ error && <p>{error}</p> }
</div>
);
}
export default App;
결론적으로는, useFetch는 안에서 결과, 로딩, 에러 상태를 반환해주는 커스텀 훅이다.