我正在使用以下 fetch post 请求在我的数据库中创建一个项目。我正在尝试使用react-query来检测请求引发的错误。
export function createItem(id, body, token) {
fetch(`${API_URL}/${id}/items`, {
method: 'post',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify(body)
})
.then(res => {
if (res.ok) {
return res.json()
}
console.log(res.status)
throw new Error("Error creating review")
})
.catch((err) => console.log(err))
}
Run Code Online (Sandbox Code Playgroud)
我的突变集如下:
const mutation = useMutation(() => {
return createItem(props.item.id, item, token)
})
Run Code Online (Sandbox Code Playgroud)
它的调用方式是:
<Button disabled={!valid} onPress={() => mutation.mutate()}>
Submit
</Button>
Run Code Online (Sandbox Code Playgroud)
我使用这个逻辑来显示错误:
{
mutation.isError && <Text>{mutation.error.message}</Text>
}
Run Code Online (Sandbox Code Playgroud)
我看到createItem函数错误带有 400 状态代码,这正是我所期望的,但反应查询未设置isError为 true。相反isSuccess …