ajax ์์ฒญํ๋ค๋ณด๋ฉด ์ด๋ฐ ๊ธฐ๋ฅ๋ค์ด ๊ฐ๋ ํ์ํด์ง๋ค.
- ๋ช์ด๋ง๋ค ์๋์ผ๋ก ๋ฐ์ดํฐ ๋ค์ ๊ฐ์ ธ์ค๊ฒ ํ๋ ค๋ฉด?
- ์์ฒญ์คํจ์ ๋ช์ด ๊ฐ๊ฒฉ์ผ๋ก ์ฌ์๋?
- ๋ค์ ํ์ด์ง ๋ฏธ๋ฆฌ๊ฐ์ ธ์ค๊ธฐ?
- ajax ์ฑ๊ณต/์คํจ์ ๊ฐ๊ฐ ๋ค๋ฅธ html์ ๋ณด์ฌ์ฃผ๋ ค๋ฉด?
1. react-query ์ค์น & ์ ํ
(terminal)
npm install react-query
(index.js)
import { QueryClient, QueryClientProvider } from "react-query" //1๋ฒ
const queryClient = new QueryClient() //2๋ฒ
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<QueryClientProvider client={queryClient}> //3๋ฒ
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</QueryClientProvider>
);
2. react-query๋ก ajax ์์ฒญํ๋ ๋ฒ
useQuery ๋ผ๋๊ฑธ ์๋จ์์ import ํด์จ ๋ค์ useQuery()๋ก ajax ์์ฒญ์ ๊ฐ์ธ๋ฉด ๋๋ค.
function App(){
let result = useQuery('์๋ช
', ()=>
axios.get('https://codingapple1.github.io/userdata.json')
.then((a)=>{ return a.data })
)
}
3. react-query์ ์ฅ์
์ฅ์ 1) ajax ์์ฒญ ์ฑ๊ณต/์คํจ/๋ก๋ฉ์ค ์ํ๋ฅผ ์ฝ๊ฒ ํ์ ํ ์ ์๋ค.
function App(){
let result = useQuery('์๋ช
', ()=>
axios.get('https://codingapple1.github.io/userdata.json')
.then((a)=>{ return a.data })
)
return (
<div>
{ result.isLoading && '๋ก๋ฉ์ค' }
{ result.error && '์๋ฌ๋จ' }
{ result.data && result.data.name }
</div>
)
}
result๋ผ๋ ๋ณ์์ ajax ํ์ฌ ์ํ๊ฐ ์์์ ์ ์ฅ๋๋ค.
- ajax์์ฒญ์ด ๋ก๋ฉ์ค : result.isLoading ์ด true
- ajax์์ฒญ์ด ์คํจ์ : result.error ๊ฐ true
- ajax์์ฒญ์ด ์ฑ๊ณต์ : result.data ์์ ๋ฐ์ดํฐ๊ฐ ๋ค์ด์จ๋ค.
์ฅ์ 2) ํ๋ง๋๋ฉด ์์์ ajax ์ฌ์์ฒญํด์ค๋ค.
- ํ์ด์ง ์ฒด๋ฅํ๊ณ ๋์ ์ผ์ ์๊ฐ์ด ๊ฒฝ๊ณผํ๊ฑฐ๋, ์ฌ์ฉ์๊ฐ ๋ค๋ฅธ ์ฐฝ์ผ๋ก ๊ฐ๋ค๊ฐ ๋ค์ ํ์ด์ง๋ก ๋์์ค๊ฑฐ๋ ๋ค์ ๋ฉ์ธํ์ด์ง๋ก ๋์๊ฐ๊ฑฐ๋ ์ด๋ฐ ์ฌ๋ฌ ๊ฒฝ์ฐ์ ์์์ ajax ์์ฒญ์ ๋ค์ ํด์ค๋ค.
- ๋น์ฐํ ์ฌ์์ฒญ ๋๋ ๋ฒ, ์ฌ์์ฒญ๊ฐ๊ฒฉ ์กฐ์ ํ๋ ๋ฒ๋ ์๋ค.
์ฅ์ 3) ์คํจ์ ์ฌ์๋ ์์์ ํด์ค๋ค.
์ ๊น ์ธํฐ๋ท์ด ๋๊ฒผ๊ฑฐ๋ ์๋ฒ๊ฐ ์ฃฝ์๊ฑฐ๋ ๊ทธ๋ฌ๋ฉด ajax ์์ฒญ์ด ์คํจํ๋ค.
์คํจํ์ ๋๋ ์ฌ์๋๋ฅผ ์์์ ํด์ค๋ค.
์ฅ์ 4) ajax๋ก ๊ฐ์ ธ์จ ๊ฒฐ๊ณผ๋ state ๊ณต์ ํ์์๋ค.
react-query์ server-state (DB ๋ฐ์ดํฐ)๋ฅผ ํ๋ก ํธ์๋์์ ์ค์๊ฐ ๋๊ธฐํํด์ฃผ๋๊ฑธ ๋์์ค๋ค.
๊ทผ๋ฐ ajax ์์ฒญ์ ๋ช์ด๋ง๋ค ๊ณ์ ๋ ๋ ค์ ๊ฐ์ ธ์ค๋ ๋ฐฉ์์ด๋ผ ์ข ๋นํจ์จ์ ์ผ ์๋ ์๋ค.
์ค์๊ฐ์ผ๋ก ์๋ฒ์์ ๋ฐ์ดํฐ๋ฅผ ์์ฃผ ๋ณด๋ด๋ ค๋ฉด ์น์์ผ์ด๋ Server-sent events ๊ฐ์ ๊ฐ๋ฒผ์ด ๋ฐฉ์๋ค๋ ์๋ค.
๊ทธ๋์ react-query๋ ajax ๊ด๋ จ ๊ธฐ๋ฅ๊ฐ๋ฐ ํธํ๊ฒ ํ ์ ์๋๋ฐ์ ์์๊ฐ ๋ ์์ต๋๋ค.
'๐ปWEB FrontEnd > ํ๋ ์์ํฌ React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ฑ๋ฅ๊ฐ์ (2) - ์ฌ๋ ๋๋ง ๋ง๋ ๋ฒ (0) | 2022.07.13 |
---|---|
์ฑ๋ฅ๊ฐ์ (1) - lazy import (0) | 2022.07.13 |
localStorage (0) | 2022.07.13 |
Redux (2) - state ๋ณ๊ฒฝ (0) | 2022.07.13 |
Redux (1) : props ์์ด state ๊ณต์ ๊ฐ๋ฅ (0) | 2022.07.13 |