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>
);
}
variables
在onSettled
中可用,即使您没有从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