Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

533
Visualizações
Fetching data error with useSWR, reactjs, nextjs

I would like fetch data from backend. I use useSWR. In function getDataUseSWR is two bugs. At line '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'.";

When I tried fetch in AlfaComponent with useSWR, it works, but when I split it to two files, then it doesn't work.

Documentation: data fetching with 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():

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

useSWR is a hook. 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

Example 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:

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

Proof of code working here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda