React, usePromise 커스텀 훅
2024. 12. 23. 16:51ㆍ웹 개발
/lib/usePromise.js
import { useState, useEffect } from 'react';
export default function usePromise(promiseCreator, deps) { // 대기 중/완료/실패/ 상태 관리하기
const [loading, setLoading] = useState(false);
const [resolved, setResolved] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const process = async () => {
setLoading(true);
try {
const resolved = await promiseCreator();
setResolved(resolved);
} catch (e) {
setError(e);
}
setLoading(false);
};
process();
}, deps);
return [loading, resolved, error];
}
사용
const list = ({params}) =>{
const [loading, response, error] = usePromise(() => {
return axios.get(URL);
}, [params])
(...)
}
'웹 개발' 카테고리의 다른 글
| React, Context, useContext Hook (1) | 2024.12.26 |
|---|---|
| React, Context + Consumer (1) | 2024.12.26 |
| React, Axios (0) | 2024.12.23 |
| Javascript, Async / Await (3) | 2024.12.20 |
| React Router DOM (3) | 2024.12.20 |