tanstack react query mutate onSettled访问PUT主体数据



Dears,

由于某种原因,我需要在PUT请求解决后访问PUT请求体。

请检查我试图准备的沙箱示例。

我的问题是-可以在onMutate中返回PUT参数,然后在onSettled中基于这些参数进行一些逻辑操作吗,例如选择性地将加载状态设置为false。

那么,为什么PUT参数是onSettled函数的第三个参数呢?

p.s.请不要争论状态管理,问题是关于onSettled的用法:)

谨致问候,MJ

import React from "react";
import { useMutation } from "react-query";
const someProps = { prop1: "key1" };
export default function App() {
const [isLoading, setIsLoading] = React.useState(false);
const { mutate } = useMutation({
mutationFn: async (someProps) =>
await fetch("https://httpbin.org/put", {
method: "PUT",
body: JSON.stringify(someProps)
}).then((response) => response.json()),
onSuccess: (responseData) => {
console.log("RESPONSE ON SUCCESS: " + JSON.stringify(responseData));
},
onMutate: (data) => {
setIsLoading(true);
console.log(
"Yes, I have access to props before I send the request: " +
JSON.stringify(data)
);
// I return the data so I can use it in on settled
return data;
},
onSettled: (arg1NotUsed, arg2NotUsed, data) => {
console.log(
"Yes, I have access to props after I receive the response: " +
JSON.stringify(data)
);
if (data) {
setIsLoading(false);
}
}
});
return (
<div>
<p>is loading: {isLoading ? "LOADING" : "IDLE"}</p>
<button onClick={() => mutate(someProps)}>trigger mutation</button>
</div>
);
}

variablesonSettled中可用,即使您没有从onMutate返回它们。onSettled接收的是:

onSettled(data, error, variables, context)

其中context是您从onSettled返回的内容。在您的示例中,您使用的是第三个参数,它是,而不是onMutate返回的值,因此您可以安全地忽略它。

也不需要单独跟踪isLoading布尔值,因为useMutation为您执行此操作,并且还返回加载状态。

export default function App() {
const { mutate, isLoading } = useMutation({
mutationFn: async (someProps) =>
await fetch("https://httpbin.org/put", {
method: "PUT",
body: JSON.stringify(someProps)
}).then((response) => response.json()),
onSuccess: (responseData) => {
console.log("RESPONSE ON SUCCESS: " + JSON.stringify(responseData));
},
onSettled: (arg1NotUsed, arg2NotUsed, data) => {
console.log(
"Yes, I have access to props after I receive the response: " +
JSON.stringify(data)
);
}
});
return (
<div>
<p>is loading: {isLoading ? "LOADING" : "IDLE"}</p>
<button onClick={() => mutate(someProps)}>trigger mutation</button>
</div>
);
}

以下是您的沙盒的一个分叉,其中包含以下更改:https://codesandbox.io/s/usequery-forked-vq8kcr?file=/src/App.js

最新更新