简体   繁体   English

使用 useSWR 获取数据错误,reactjs,nextjs

[英]Fetching data error with useSWR, reactjs, nextjs

I would like fetch data from backend.我想从后端获取数据。 I use useSWR.我使用 useSWR。 In function getDataUseSWR is two bugs.在 function getDataUseSWR 是两个错误。 At line 'fetch(url).then' errors: 1:"Expected 0 arguments, but got 1.";在“fetch(url).then”行错误:1:“预期为 0 arguments,但得到了 1。”;
2: "Property 'then' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined) => Promise'."; 2:“属性‘then’在类型‘(input: RequestInfo, init?: RequestInit | undefined) => Promise’上不存在。”;

When I tried fetch in AlfaComponent with useSWR, it works, but when I split it to two files, then it doesn't work.当我尝试使用 useSWR 在 AlfaComponent 中获取时,它起作用了,但是当我将它分成两个文件时,它就不起作用了。

Documentation: data fetching with useSWR文档:使用 useSWR 获取数据

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

Code with fetch():使用 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 is a hook. useSWR 是一个钩子。 You are trying to run hook in await function. You should create a class in /lib folder and call this class to fetch data on Client side您正在尝试在等待 function 中运行挂钩。您应该在/lib文件夹中创建一个 class 并调用此 class 以在客户端获取数据

Example class:示例 class:

export class GeneralFunctions {

    static async getDataUseSWR (urlInput: string): Promise<any> {
    //your body of class function
    // do not use hooks here
    }
}

Than you can call you function, something like:比你可以叫你 function,像:

const response = await GeneralFunctions.getDataUseSWR('http://localhost:5000/data/export')

But I don't understand why don't you just但我不明白你为什么不

//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 is similar to useEffect hook useSWR 类似于 useEffect hook

Proof of code working here代码证明这里工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM