Home > Enterprise >  Fetching image from Supabase storage through database table returns undefined URL
Fetching image from Supabase storage through database table returns undefined URL

Time:12-14

I am building an app in Next.js, which fetches dynamic data from a Supabase table. The table (called product) has several data points (title, description, image). My table in Supabase looks like this: enter image description here

My problem is that both the description and the title are being pulled in dynamically, populating my home page properly. What is failing is the image. Images are stored in a public bucket that looks like this:

enter image description here

The way I'm attempting to pull the image in dynamically is as follows:

import { supabase } from "../utils/supabase";
import Link from "next/link";
import { useUser } from "../context/user";
import Image from "next/dist/client/image";

export default function Home({ products, tile_url }) {
  const { user } = useUser();

  const {data:image_url} = supabase.storage.from("games").getPublicUrl(tile_url);
  console.log(image_url.publicURL);

  return (
    <div className="body w-full h-screen py-16">
      <div className="w-full max-w-3xl mx-auto px-2">
        {products.map((product) => (
          <Link
            key={product.id}
            href={`/${product.id}`}
          >
            <a className="p-8 h-40 mb-4 rounded element text-xl flex">
             
              <img src={image_url.publicURL} alt="" />
              {product.title}
            </a>
          </Link>
        ))}
      </div>
    </div>
  );
}

export const getStaticProps = async () => {
  const { data: products } = await supabase.from("product").select("*");

  return {
    props: {
      products,
    },
  };
};

The image is not returned in the frontend. The console.log returns the url, but instead of the image name, it pastes undefined a the end:

https://[project_identifier].supabase.co/storage/v1/object/public/games/undefined

The expected outcome would be:

https://[project_identifier].supabase.co/storage/v1/object/public/games/gameOneGameTile.jpeg

Any ideas as to what I am doing wrong? Thank you in advance!

EDIT:

Based on a response from @dshukertjr on this question, I have included the path to the image in the table, to be able to use the column name to fetch the data. However, nothing has changed. enter image description here

CodePudding user response:

What you need to pass to the getPublicUrl() function is the path to the image within the bucket for example like this:

  const pathToImage = 'game_one/gameOneGameTile.jpeg'

  const {data:image_url} = supabase.storage.from("games").getPublicUrl(pathToImage);

You are passing tile_url in your code. If you want to keep it that way, the path to the image needs to be saved in your product table under tile_url column for each row to be able to display an image.

  • Related