SWR 与材质 UI 数据网格

发布于 2025-01-12 09:43:34 字数 466 浏览 3 评论 0原文

我正在使用 SWR 获取数据来填充数据网格的行。

fetcherGet = (url: any) => axios.get(url).then((res: {data: any}) => res.data)

let {data: customers = []} = useSWR(
    [ROUTES.GET_CUSTOMERS_BY_ROUTE],
    fetcherGet
  )
  return (
     <DataGrid rows={customers} columns={columns} />
  )

问题是,当我切换到另一个选项卡并返回应用程序时,SWR 返回一个未定义的值,因此分配了一个空数组,并且网格变空。然后数据来了,网格再次获取数据。 如果我保留删除[],数据网格会出现错误,因为未定义没有长度属性。

在获取数据时处理未定义返回以防止在获取数据之前清空网格的最佳方法是什么?

I am using SWR to get the data to populate the rows of the Data Grid

fetcherGet = (url: any) => axios.get(url).then((res: {data: any}) => res.data)

let {data: customers = []} = useSWR(
    [ROUTES.GET_CUSTOMERS_BY_ROUTE],
    fetcherGet
  )
  return (
     <DataGrid rows={customers} columns={columns} />
  )

The issue is that when I switch to another tab and come back to the app, SWR return an undefined so an empty array is assigned and the grid gets empty. Then the data comes and the grid gets the data again.
If I keep remove [], Data Grid has an error cause undefined does not have a length attribute.

What is the best way to handle the undefined return while the data is fetched to prevent the grid to be emptied before getting the data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平生欢 2025-01-19 09:43:34

我在 SWR + Next.js + MUI 中遇到了同样的问题

这是 Typesctipt 中的一个快速而肮脏的解决方案

function useUsers() {
    const { data, error } = useSWR('/api/users/', fetcher)
    
  
    return {
      users: data !== undefined ? data : false,
      isLoading: !error && !data,
      isError: error
    }
  }

您基本上可以过滤自定义 getter 挂钩的返回值,用 覆盖 undefined 值>假

此代码片段基于 SWR 的入门指南 https://swr。 vercel.app/docs/getting-started#make-it-reusable

I've faced the same problem with SWR + Next.js + MUI

Here is a quick and dirty solution in Typesctipt

function useUsers() {
    const { data, error } = useSWR('/api/users/', fetcher)
    
  
    return {
      users: data !== undefined ? data : false,
      isLoading: !error && !data,
      isError: error
    }
  }

You could basically filter the return value of your custom getter hook, overriding undefined value with false.

This code fragment is based on SWR's getting started guide https://swr.vercel.app/docs/getting-started#make-it-reusable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文