Next.js Discord

Discord Forum

SWR Fetching loading not finishing

Unanswered
Mini Satin posted this in #help-forum
Open in Discord
Avatar
Mini SatinOP
Hey guys! I am trying to use SWR for client-side components so I don't use useEffect with API requests, so I`ve created a hook to simplify my requests.
Image

3 Replies

Avatar
Mini SatinOP
import useSWR from "swr";

export function useFetch<T = any>(url: string) {
  // @ts-expect-error Spread inside tuple
  const fetcher = (...args) => fetch(...args).then((res) => res.json());
  const { data, error, isLoading } = useSWR(url, fetcher);

  console.log(url);

  return { data: data as T, error, isLoading };
}


But its making the request forever (the image from the post)

And this is how I am calling the function

"use client";
import { FormEvent, useRef } from "react";
import { Input } from "./Input";
import { TextArea } from "./TextArea";
import { Button } from "./Button";
import { useFetch } from "@/hooks/useFetch";
import { TABLES } from "@/enums";

type FormData = {
  name: string;
  phone: string;
  email: string;
  message: string;
};

export function ContactUsForm() {
  // const response = useFetch(
  //   `${process.env.NEXT_PUBLIC_API_URL}/${
  //     TABLES.CONTACT_US_FORM_FIELDS
  //   }?sortBy=order&active=1&timestamp=${Date.now()}`,
  // );
  // console.log(response);
  console.log(`render`);
  const nameRef = useRef<HTMLInputElement>(null);
  const phoneRef = useRef<HTMLInputElement>(null);
  const emailRef = useRef<HTMLInputElement>(null);
  const messageRef = useRef<HTMLTextAreaElement>(null);

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();

    const data: FormData = {
      name: nameRef.current?.value || "",
      phone: phoneRef.current?.value || "",
      email: emailRef.current?.value || "",
      message: messageRef.current?.value || "",
    };

    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-6" lang="pt">
      <Input
        id="name"
        name="name"
        ref={nameRef}
        label="Nome Completo *"
        required
      />

      <Input
        id="phone"
        name="phone"
        ref={phoneRef}
        label="Telefone *"
        type="tel"
        required
      />

      <Input
        id="email"
        name="email"
        ref={emailRef}
        label="E-Mail *"
        type="email"
        required
      />

      <TextArea
        id="message"
        name="message"
        ref={messageRef}
        label="Mensagem *"
        required
      />

      <Button className="self-start font-semibold text-xl lg:text-2xl">
        Enviar
      </Button>
    </form>
  );
}
The URL is right because insomnia returns me right away
Image
Avatar
Mini SatinOP
Anyone?