在 SWR 中使用 mutate 重新验证数据 - 我应该使用哪个? [英] Revalidating data using mutate in SWR - Which should I use?

查看:277
本文介绍了在 SWR 中使用 mutate 重新验证数据 - 我应该使用哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,每次用户创建新专辑时,发布请求响应都会以更新的专辑列表作为响应.

In my app every time the user creates a new album the post request response responds with a list of the updated list of albums.

为了提供更好的用户体验,我希望用户无需刷新页面即可看到应用中的新内容.

To provide a better user experience, I wanted the user to see the new content in the app without having to refresh the page.

我知道 SWR 的 mutate 的存在,但到目前为止,我无法让它发挥作用.

I'm aware of the existence of SWR's mutate, but so far, I couldn't make it work.

我试图在我的钩子中设置一个 1000 毫秒的 refreshInterval,但我想知道如何通过使用 mutate 来做到这一点.这是我尝试过的:

I tried to set a 1000ms refreshInterval in my hook, but I wanted to know how to do it by using the mutate. Here's what I tried:

SWR 钩子

const fetcher = async (url: string, param: string) => {
    const res = await fetch(url + param);
    
   return res.json();
};


const { data, error } = useSWR(
 ["/api/albums/list?id=", appUser.id],
  (url, params) => fetcher(url, params)
);

createAlbum 函数内部:

const data = await response.json();

mutate("/api/albums/list", data.newAlbums, false);

我很乐意得到一些反馈.

I would be happy to get some feedback.

推荐答案

你的代码基本正确,问题在于SWR 内部散列用于查询/变异的键.因此,mutate 函数使用的密钥根本没有在缓存中注册.

Your code is almost correct, the issue lies in the fact that SWR internally hashes the keys used for queries/mutation. Therefore, the key used by the mutate function is simply not registered in the cache.

要使用swr直接导出的mutate函数解决这个问题,只需将相同的密钥传递给useSWR变异.

To solve this problem using the mutate function exported directly by swr, it will suffice just to pass the same key to both useSWR and mutate.

mutate(["/api/albums/list?id=", appUser.id]);

这将使散列键的缓存无效.从原始钩子中检索到的数据将过时,因此将再次被提取.

This will invalidate the cache for the hashed key. The data retrieved from your original hook will go stale, and will therefore be fetched again.

另一种选择是利用绑定到 swr 密钥的 mutate 函数.

Another option is to take advantage of the mutate function bound to swr's key.

const { data, error, mutate } = useSWR(
   ["/api/albums/list?id=", appUser.id],
   (url, params) => fetcher(url, params)
);

/*
 * Now you can just call `mutate()` without specifying `key` argument
 */

文档:https://github.com/vercel/swr#bound-mutate

为了完整性,正如您所说,另一种选择是设置 refreshInterval 道具的值.在需要时强制重新获取:

For completeness, as you said, one other option would be just to set the value of refreshInterval prop. Forcing a refetch when desired:

const { data, error } = useSWR(
   ["/api/albums/list?id=", appUser.id],
   (url, params) => fetcher(url, params),
   {
     refreshInterval: 1000, 
   }
);

这篇关于在 SWR 中使用 mutate 重新验证数据 - 我应该使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆