React Query 学习 3 修改(Mutations)
2022-12-08 本文已影响0人
吴摩西
不同于查询,修改用来向服务器发送 创建/更新/删除 请求。
function App() {
const mutation = useMutation(newTodo => {
return axios.post('/todos', newTodo)
});
return (
<button
onClick={() => {
mutation.mutate({ id: new Date(), title: 'Do Laundry' })
}}
>
Create Todo
</button>
);
}
可以通过 mutation.reset()
重制 mutation 的状态,例如当请求出错后,清除掉错误状态。
修改后,无效某个 query
import { useMutation, useQueryClient } from 'react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = useMutation(addTodo, {
onSuccess: () => {
queryClient.invalidateQueries('todos')
queryClient.invalidateQueries('reminders')
},
})
修改后,更新 query
同服务器更新以后,可以通过 setQueryData
更新 query
const useMutateTodo = () => {
const queryClient = useQueryClient()
return useMutation(editTodo, {
// Notice the second argument is the variables object that the `mutate` function receives
onSuccess: (data, variables) => {
queryClient.setQueryData(['todo', { id: variables.id }], data)
},
})
}
取消请求
React Query 自带一个 AbortController,可以通过 signal
相应请求的取消。这会在请求发出,但是组建已经销毁的时候帮助取消请求。如果不取消,返回的数据会被缓存。
import axios from 'axios'
const query = useQuery('todos', ({ signal }) =>
axios.get('/todos', {
// Pass the signal to `axios`
signal,
})
)
请求筛选
修改和查询,共享某些筛选条件。可以对某些请求进行批量的操作,例如取消,重取等。
// Cancel all queries
await queryClient.cancelQueries()
// Remove all inactive queries that begin with `posts` in the key
// this would remove the caches
queryClient.removeQueries('posts', { inactive: true })
// Refetch all active queries
await queryClient.refetchQueries({ active: true })
// Refetch all active queries that begin with `posts` in the key
await queryClient.refetchQueries('posts', { active: true })