๐ customHooks๋ก getApi ์ฝ๋ ๊ด๋ฆฌํ๊ธฐ
fetch
ํน์ axios
๋ฅผ ์ฌ์ฉํ์ฌ api
๋ฅผ ๋ฐ์์ฌ ๋ ๊ธฐ์กด์๋ app.tsx
ํ์ผ ๋ด์์ useEffect
๋ฅผ ์ฌ์ฉํ์ฌ api
๋ฅผ ๋ฐ์์ค๋ ์ฝ๋๋ฅผ ๋ชจ๋ ์์ฑํ๋ค. ๊ทธ๋ฌ๋, app.tsx
์ api
์ ๊ด๋ จ๋ ์ฝ๋๋ฅผ ๋ชจ๋ ์์ฑํ๋ฉด ๋ค๋ฅธ ๋ก์ง์ฝ๋๋ฅผ ๋ณด๋๋ฐ ์ ๊ฒฝ ์ฐ์ฌ์ ๋ค๋ฅธ ๊ณณ์ผ๋ก ์ฎ๊ฒจ์ผ๊ฒ ๋ค๋ ์๊ฐ์ด ๋ ์ฌ๋๊ณ hooks
ํด๋๋ฅผ ์์ฑํ์ฌ customHooks
๋ก ๋ฐ๋ก ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ์ด app.tsx
์ ๊ฐ๋
์ฑ์ ์ฆ๊ฐ์ํจ๋ค๊ณ ์๊ฐํ๋ค.
data
, loading
, error
๊ฐ์ export
ํ ๋ ํ์
์ถ๋ก ์ด ๋ช
ํํ๊ฒ ๋์ง ์๋ ๊ฒฝ์ฐ๊ฐ ์์ด as
๋ฌธ์ ์ฌ์ฉํด์ ์ด๋ค ํ์
์ธ์ง ๋ช
์ํ๋ค. as
๋ฌธ ๋์ interface
๋ฅผ usePosts
๋ฆฌํด๊ฐ์ ๋ถ์ฌ์ค๋ ๋๋๋ฐ ์ด๋๋ {}
๋ก return
ํ๊ณ app.tsx
์์ ๋ถ๋ฌ์ฌ ๋๋ {}
๋ก ๋ถ๋ฌ์ค๋๊ฒ์ ์์ง ๋ง์.
์์ธํ ์ฝ๋๋ ๊นํ๋ธ๋ฅผ ์ฐธ๊ณ ํด์ฃผ์ธ์ :)
// hooks/usePosts/index.tsx
// use alias(as)
import axios, { AxiosResponse } from "axios";
import { useEffect, useState } from "react";
import { Data } from "../../types";
const usePosts = () => {
const [data, setData] = useState<Data[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<Error>();
useEffect(() => {
setLoading(true);
const getPosts = async () => {
try {
const response: AxiosResponse<any> = await axios.get(
"https://jsonplaceholder.typicode.com/posts/"
);
setData(response.data);
setLoading(false);
} catch (e) {
setError(e);
setLoading(false);
}
};
getPosts();
}, []);
return [data, loading, error] as [Data[], boolean, Error];
};
export default usePosts;
// hooks/usePosts/index.tsx
// use interface
import axios, { AxiosResponse } from "axios";
import { useEffect, useState } from "react";
import { Data } from "../../types";
interface Response {
data: Data[];
loading: boolean;
error?: Error;
}
const usePosts = (): Response => {
const [data, setData] = useState<Data[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<Error>();
useEffect(() => {
setLoading(true);
const getPosts = async () => {
try {
const response: AxiosResponse<any> = await axios.get(
"https://jsonplaceholder.typicode.com/posts/"
);
setData(response.data);
setLoading(false);
} catch (e) {
setError(e);
setLoading(false);
}
};
getPosts();
}, []);
return {data, loading, error};
};
export default usePosts;
// app.tsx
import Container from "./components/container";
import Card from "./components/molecules/card";
import usePosts from "./hooks/useposts";
const App = () => {
const [data, loading, error] = usePosts();
if (loading) {
return <div>loading...</div>;
}
if (error){
return <div>Error...</div>
}
return (
<Container>
{data.map((item) => (
<Card key={item.id} item={item}></Card>
))}
</Container>
);
};
export default App;
๋๊ธ