useAsync() ๋ react-async ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ์ ๊ณตํ๋ hooks ๋ค.
react component ์์ ๋น๋๊ธฐ ํต์ ์ผ๋ก ๋ฐ์์จ ๋ฐ์ดํฐ๋ฅผ ์ธ ๋, ํจ์ํ ์ปดํฌ๋ํธ ์์ async ๋ฅผ ๋ถ์ฌ์ฃผ๋ฉด ์ค๋ฅ๊ฐ ๋ฌ๋ค.
์ด๋ด ๋ useAsync() ๋ฅผ ์ฌ์ฉํ๋ค.
์ฌ์ฉ๋ฒ์ ์ด๋ ๋ค.
export const searchDetailById = async ({ id }) => {
const { data: result } = await axios.get(
`https://www.serveradress?id=${id}`
);
return result;
};
import { useAsync } from "react-async";
import { searchDetailById } from "./Data";
function Test({id}) {
const {
data: detail,
error,
isLoading,
} = useAsync({
promiseFn: searchDetailById,
id: id,
watch: id,
});
if (isLoading) return <div>loding...</div>;
if (error || !detail) return <div>error!</div>;
return (<div> detail.name </div>);
}
useAsync() ๋ ๊ฒฐ๊ณผ๋ก {data, error, isLoding} ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.
ํ์ํ ํ๋ผ๋ฏธํฐ๋ {promiseFn, id, watch} ์ด๋ค.
promiseFn ์ ๋น๋๊ธฐ ํต์ ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ค๋ ํจ์์ด๊ณ id์ watch ๋ ํด๋น ํจ์์ ๋ณด๋ผ ์ธ์๋ค. {id, watch} ๊ฐ์ฒด๋ก ๋ณด๋ด์ง๋ค.
์ด๋ ๊ฒ ํ๋ฉด searchDetailById({id, watch}) ๋ฅผ ์คํ์์ผ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ data, error, isLoading ์ผ๋ก ๋ฐํํ๋ค.
๋ฐ์ํ