无法在Next.js中使用Array.find来处理useSWR返回的结果。

huangapple go评论75阅读模式
英文:

Fail to use Array.find for the useSWR return in nextjs

问题

代码部分不翻译,以下是翻译好的部分:

我在进行以下操作:

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 出错");
    }
  });
  await Promise.all(promises);
  return new Response(JSON.stringify(events), { status: 200 });

然而,出现了错误:

TypeError: 无法读取未定义的属性 (读取 'find')

我可以问一下如何解决它吗?

英文:

I am doing:

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"))

The api route:

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 });

However, the error:

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

May I ask how I can solve it?

答案1

得分: 0

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

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

// 检查是否有错误
if (error) return <h1>{`出错了:${error}`}</h1>;

// 如果数据不可用,返回
if (!data) return <h1>Loading...</h1>;

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

Check data before executing find() method on it.

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

// check for error
if(error) return &lt;h1&gt;`Something went wrong: ${error}`&lt;/h1&gt;

// if data is not available, return
if(!data) return &lt;h1&gt;Loading...&lt;/h1&gt;

console.log(data.find(d =&gt; d.id === &quot;123&quot;));

答案2

得分: 0

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

尝试这样做....

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

Try to use filter() method on array

Try this....

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

答案3

得分: 0

你需要考虑加载状态。useSWR 钩子返回一个 isLoading 属性,所以你可以在数据加载时显示加载状态。

https://swr.vercel.app/

import useSWR from 'swr';

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher);

  if (error) return <div>加载失败</div>;
  if (isLoading) return <div>加载中...</div>;
  return <div>你好{data.name}</div>;
}
英文:

You need to account for the loading state. The useSWR hook returns an isLoading property so you can display a loading state while the data loads.

https://swr.vercel.app/

import useSWR from &#39;swr&#39;
 
function Profile() {
  const { data, error, isLoading } = useSWR(&#39;/api/user&#39;, fetcher)
 
  if (error) return &lt;div&gt;failed to load&lt;/div&gt;
  if (isLoading) return &lt;div&gt;loading...&lt;/div&gt;
  return &lt;div&gt;hello {data.name}!&lt;/div&gt;
}

huangapple
  • 本文由 发表于 2023年7月20日 12:12:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定