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

标签 reactjs next.js swr

我希望 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/

相关文章:

javascript - React - 全部展开/折叠

javascript - Highcharts 添加工具提示,其中有一个指向系列的小箭头

css - 如何使其父 div 的 NextJS Image 组件的高度和宽度为 100%?

reactjs - SWR维护的缓存在哪里,客户端还是服务器端?

javascript - 如何防止 react-query 最初获取但启用重新获取?

javascript - Javascript 如何知道何时执行通过引用隐式传递的函数? react 示例

javascript - 类型错误 : route is undefined and undefined is not an object (evaluating 'route.params' )

next.js - 尝试使用 React-Leaflet(T3 堆栈)构建 nextjs 时出错

javascript - 如何在 Next.js 中重新加载时强制执行 i18n 语言环境 slug 并实现 i18n 一致性?

reactjs - 使用 SWR 单击时向 API 路由发出请求时出现太多重新呈现错误