无法在nextjs中为useSWR返回使用Array.find

x33g5p2x  于 2023-08-04  发布在  其他
关注(0)|答案(3)|浏览(90)

我正在做:

const fetcher = (url: string) => axios.get(url).then((r) => r.data);

const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000})
console.log(data.find(d => d.id === "123"))

字符串
API路由:

const promises = matchString.split(",").map(async (match: string) => {
    try {
      events.push(await Events.find({ name: match }).then((res) => res[0]))
    } catch (error) {
      events.push(error)
      console.log("model/route.js error")
    }
  })
  await Promise.all(promises)
  return new Response(JSON.stringify(events), { status: 200 });


然而,错误:

TypeError: Cannot read properties of undefined (reading 'find')


我能问一下怎么解决吗?

bgibtngc

bgibtngc1#

在执行find()方法之前检查数据。

const {data, error} = useSWR("api/data", fetcher, {refreshInterval: 10000});

// check for error
if(error) return <h1>`Something went wrong: ${error}`</h1>

// if data is not available, return
if(!data) return <h1>Loading...</h1>

console.log(data.find(d => d.id === "123"));

字符串

pkmbmrz7

pkmbmrz72#

尝试在数组上使用filter()方法
试试这个。。。

const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000})
console.log(data?.filter(d => d.id === "123"));

字符串

6yjfywim

6yjfywim3#

您需要考虑加载状态。useSWR钩子返回一个isLoading属性,以便在数据加载时显示加载状态。
https://swr.vercel.app/

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
 
  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

字符串

相关问题