@aspida/react-query
Getting Started
Installation
Make HTTP request from application
src/index.ts
import { useQueryClient, useMutation, QueryClient, QueryClientProvider } from 'react-query'
import { useAspidaQuery } from "@aspida/react-query"
import aspida from "@aspida/axios"
import api from "../api/$api"
const client = api(aspida())
const queryClient = new QueryClient()
function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
function postTodo(body: { id: number; title: string }) {
return client.todos.$post({ body })
}
function Todos() {
const queryClient = useQueryClient()
const query = useAspidaQuery(client.todos, { query: { limit: 10 }})
const mutation = useMutation(postTodo, {
onSuccess: () => {
queryClient.invalidateQueries(client.todos.$path({ query: { limit: 10 }}))
},
})
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'))
Get response body/status/headers
src/index.ts
import { useMutation, QueryClient, QueryClientProvider } from 'react-query'
import { useAspidaQuery } from "@aspida/react-query"
import aspida from "@aspida/axios"
import api from "../api/$api"
const client = api(aspida())
const queryClient = new QueryClient()
function App() {
return (
<QueryClientProvider client={queryClient}>
<Profile />
</QueryClientProvider>
)
}
function Profile() {
const { data, error } = useAspidaQuery(
client.user._userId(123),
'get',
{ query: { name: 'mario' } }
)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return (
<>
<div>Status: {data.status}</div>
<div>Headers: {JSON.stringify(data.headers)}</div>
<div>Name: {data.body.name}</div>
</>
)
}
render(<App />, document.getElementById('root'))
useAspidaQuery(client.user._userId(123), { query })
is an alias of useAspidaQuery(client.user._userId(123), "$get", { query })
Use with React Query options
src/index.ts
import { useMutation, QueryClient, QueryClientProvider } from 'react-query'
import { useAspidaQuery } from "@aspida/react-query"
import aspida from "@aspida/axios"
import api from "../api/$api"
const client = api(aspida())
const queryClient = new QueryClient()
function App() {
return (
<QueryClientProvider client={queryClient}>
<Profile />
</QueryClientProvider>
)
}
function Profile() {
const { data, error } = useAspidaQuery(
client.user._userId(123),
{
query: { name: 'mario' },
refetchOnMount: true,
initialData: { name: 'anonymous' }
}
)
if (error) return <div>failed to load</div>
return <div>hello {data.name}!</div>
}
render(<App />, document.getElementById('root'))
License
@aspida/react-query is licensed under a MIT License.