React Query
React application์์ ์๋ฒ ์ํ์ fetching, caching, synchronizing and updating์ ๋์์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from 'react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
fetcher
ํจ์์argument
๊ฐ ํ์ํ ๊ฒฝ์ฐ ์ต๋ช ํจ์๋ฅผ ๋ง๋ค์ดfetcher
ํจ์๋ฅผ ๋ฆฌํดํจkey
๋ ์บ์ ์์คํ ์ ์ ์ฅ๋๊ณ ์๋ํ๊ธฐ ์ํด ๊ณ ์ ํ ๊ฐ์ด์ด์ผ ํจ
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery('todos', getTodos)
// TypeScript and argument
const { isLoading, data } = useQuery<Interface>('todos', () => getTodos(argument))
// Mutations
const mutation = useMutation(postTodo, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('todos')
},
})
return (
<div>
<ul>
{query.data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<button
onClick={() => {
mutation.mutate({
id: Date.now(),
title: 'Do Laundry',
})
}}
>
Add Todo
</button>
</div>
)
}
render(<App />, document.getElementById('root'))
React Query Devtools
React Query์ ๋ชจ๋ ๋ด๋ถ ์๋์ ์๊ฐํ ํ์ฌ ๋ณด์ฌ์ค
์บ์์ ์ด๋ค query๊ฐ ์๋์ง์ Data Explorer ์ ๊ณต
Import the Devtools
import { ReactQueryDevtools } from "react-query/devtools";
Floating Mode
function App() {
return (
<QueryClientProvider client={queryClient}>
// The rest of your application
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
Last updated