Me gustaría obtener datos del backend. Yo uso useSWR. En la función getDataUseSWR hay dos errores. En la línea 'fetch(url).then' errores: 1:"Esperaba 0 argumentos, pero obtuvo 1.";
2: "La propiedad 'entonces' no existe en el tipo '(entrada: RequestInfo, init?: RequestInit | undefined) => Promesa'.";
Cuando intenté buscar en AlfaComponent con useSWR, funcionó, pero cuando lo dividí en dos archivos, no funcionó.
Documentación: obtención de datos con 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 } }Código con 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 es un gancho. Está intentando ejecutar el gancho en la función de espera. Debe crear una clase en la carpeta /lib y llamar a esta clase para obtener datos en el lado del cliente
Clase de ejemplo:
export class GeneralFunctions { static async getDataUseSWR (urlInput: string): Promise<any> { //your body of class function // do not use hooks here } }De lo que puedes llamar tu función, algo como:
const response = await GeneralFunctions.getDataUseSWR('http://localhost:5000/data/export')Pero no entiendo por qué no simplemente
//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 es similar al gancho useEffect
Prueba de código trabajando aquí