gpt4 book ai didi

reactjs - SWR:改变数据时立即更新 UI

转载 作者:行者123 更新时间:2023-12-05 01:26:22 25 4
gpt4 key购买 nike

我希望 UI 中的数据立即更新,而不是等待 SWR 与数据库同步。

我试过关注 the docs ,但 UI 仍然不会自动更新(我切换并返回我的浏览器以更新它)。这是代码:

import useSWR, { useSWRConfig } from "swr";

export default function Tasks() {
const { mutate } = useSWRConfig()
const { data } = useSWR("/api/tasks", (...args) =>
fetch(...args).then((res) => res.json())
)

const deleteTask = async (taskId) => {
const newData = data.filter((task) => task.id !== taskId)

mutate(`/api/tasks/${taskId}`, newData, false)

await fetch(`/api/tasks/${taskId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
})

mutate(`/api/tasks/${taskId}`)
}

if (!data) return <p>loading</p>

return (
<div>
{data.map((task) => (
<div key={task.id}>
<div>{task.content}</div>
<button onClick={() => deleteTask(task.id)}>Delete</button>
</div>
))}
</div>
)
}

最佳答案

问题是您调用了错误的 mutate 函数。当您在 mutate(`/api/tasks/${taskId}`)

上调用 mutate 时,您期望 data 得到刷新

首先做如下修改

const { data, mutate: mutateList } = useSWR("/api/tasks", (...args) =>
fetch(...args).then((res) => res.json())
)

现在,在您的删除任务中执行以下操作

const deleteTask = async (taskId) => {
const newData = data.filter((task) => task.id !== taskId)

// The useSWR("/api/tasks"...) returns a mutate method bound to swr's key, use it!
// Passing false will prevent revalidation so a fetch request
// won't be made to your api on the other hand if you pass true
// then a fetch request will be made to your api. In both cases
// you should see your cache refreshed immediately and that
// should update your UI. Since you haven't as yet updated your
// backend i.e. you are calling mutate _before_ calling your
// api, you'll want to pass false as 2nd argument.
// Had you called mutate after calling your api then you could
// have passed true as second argument to revalidate your cached
// data. Passing true as second argument in the function below
// doesn't make sense since you have yet to update your
// server/backend.
await mutateList(newData, false);

await fetch(`/api/tasks/${taskId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
})
}

关于reactjs - SWR:改变数据时立即更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70340258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com