英文:
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("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"));
答案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("api/data", fetcher, {refreshInterval: 10000})
console.log(data?.filter(d => d.id === "123"));
答案3
得分: 0
你需要考虑加载状态。useSWR
钩子返回一个 isLoading
属性,所以你可以在数据加载时显示加载状态。
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.
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>
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论