[英]Fetching data error with useSWR, reactjs, nextjs
我想從后端獲取數據。 我使用 useSWR。 在 function getDataUseSWR 是兩個錯誤。 在“fetch(url).then”行錯誤:1:“預期為 0 arguments,但得到了 1。”;
2:“屬性‘then’在類型‘(input: RequestInfo, init?: RequestInit | undefined) => Promise’上不存在。”;
當我嘗試使用 useSWR 在 AlfaComponent 中獲取時,它起作用了,但是當我將它分成兩個文件時,它就不起作用了。
import useSWR from 'swr'
export async function getDataUseSWR (urlInput: string): Promise<any> {
const fetcher = (url) => fetch(url).then((res) => res.json()); // <- here are errors, at 'fetch(url).then' errors:
// 1:"Expected 0 arguments, but got 1.";
// 2: "Property 'then' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'."
let { data, error } = useSWR(`${urlInput}`, fetcher)
if (data.ok) {
return data
} else {
return error
}
}
使用 fetch() 的代碼:
import React, { useState } from 'react';
import type { NextPage } from 'next'
import { useRouter } from 'next/router';
import { getDataUseSWR } from "../requests/ser";
type Props = {}
const AlfaComponent: NextPage = (props: Props) => {
const [data, setData] = useState();
const getData = async () => {
const response = await getDataUseSWR('http://localhost:5000/data/export')
setData(response)
}
getData()
return (
<>
<div />
.
.
.
</>
);
};
export default AlfaComponent;
useSWR 是一個鈎子。 您正在嘗試在等待 function 中運行掛鈎。您應該在/lib
文件夾中創建一個 class 並調用此 class 以在客戶端獲取數據
示例 class:
export class GeneralFunctions {
static async getDataUseSWR (urlInput: string): Promise<any> {
//your body of class function
// do not use hooks here
}
}
比你可以叫你 function,像:
const response = await GeneralFunctions.getDataUseSWR('http://localhost:5000/data/export')
但我不明白你為什么不
//don't need absolute path on client side
// you should call your api endpoint
const {data: incomingData, error: incomingError) = useSWR('/data/export')
if (incomingData){
return <div>ok!</div>
}
if (incomingError){
return <div>error produced</div>
}
return <div>Loading...</div>
useSWR 類似於 useEffect hook
代碼證明在這里工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.