Search code examples
reactjsnext.jssupabase

NextJS, SWR, Supabase. Why I can't fetch data?


I can't understand the problem, I'm doing a simple data fetching and I can't get it.

Checked on a third-party API, the data from the url is displayed. And here what only I did not carry out manipulations - nothing helps.

My component:

import { supabase } from "@/lib/supabaseClient";

import useSWR from "swr";

type Product = {
  id: number;
  name: string;
  price: number;
  description: string;
  wallet: string;
  created_at: string | null;
  updated_at: string | null;
};

const fetcher = (url: RequestInfo | URL) =>
  fetch(url).then((res) => res.json());

function Products() {
  const { data, error, isLoading } = useSWR(
    () => supabase.from("products").select("*"),
    fetcher
  );

  console.log(data);

  return (
    <div className="mx-[12px] mb-[12px] flex flex-col items-center justify-center gap-[12px] gap-[24px] rounded-large border border-dashed border-zinc-700 bg-[#161618]/50 p-[36px] text-white hover:bg-gray-500/20  lg:flex-row">
      {data?.map((product: Product) => (
        <div key={product.id}>{product.name}</div>
      ))}
    </div>
  );
}

export { Products };

My subabase Client:

import { createClient } from "@supabase/supabase-js";

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error("Supabase URL or Key is undefined");
}

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

I am getting infinite loading and hitting the server with 404


Solution

  • I'd recommend using the Supabase Cache Helpers for this: https://supabase-cache-helpers.vercel.app/postgrest/getting-started

    import { useQuery } from "@supabase-cache-helpers/postgrest-swr";
     
    const client = createClient<Database>(
      process.env.SUPABASE_URL,
      process.env.SUPABASE_ANON_KEY
    );
     
    function Page() {
      // Define the query, and its automatically parsed into an unique cache key.
      // `count` queries are supported, too
      const { data, count } = useQuery(
        client
          .from("contact")
          .select("id,username,ticket_number", { count: "exact" })
          .eq("username", "psteinroe"),
        {
          revalidateOnFocus: false,
          revalidateOnReconnect: false,
        }
      );
      return <div>...</div>;
    }