小编Ada*_*ord的帖子

React-query 突变 isError 未在失败的 POST 上设置 true

我正在使用以下 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 …

fetch reactjs react-native expo react-query

9
推荐指数
1
解决办法
1万
查看次数

标签 统计

expo ×1

fetch ×1

react-native ×1

react-query ×1

reactjs ×1