Console.Log Returning Undefined

19 replies
Last updated: May 16, 2022
import React from 'react';
import { Link } from "react-router-dom";
import Header from "../components/Header";
import "./Home.css";
import {Carousel, Card, Image} from 'antd';
import {client} from "../lib/client";


const Home = ({products,bannerData}) => {

  return(
      <>
        <div className="container">
          <Header/>
          <Carousel autoplay className="carousel">
            {bannerData?.map((e) => {
              return <img src={e} className="carousel-img" alt="carousel"></img>;
            })}
          </Carousel>
          <div className="cards">
            <Card className="card">{products?.map((product)=>{
              return(
                  <div key={product.Slug}>
                  <h1>{product.Name}</h1>
                  <img src={product.Image} alt={product.Name} className="card-content"/>
                  <br />
                  <Link to="/categories" state={product.Genre} className="link">
                    Shop Now
                  </Link>
                  </div>
              )
            })}


            </Card>
          </div>
        </div>
      </>
  )


}
export const getServerSideProps = async () => {
  const query = `*[_type == "product"]`;
  const products = await client.fetch(query);

  const bannerQuery = `*[_type == "banner"]`;
  const bannerData = await client.fetch(bannerQuery);

  return {
    props: { products, bannerData }
  }
}

export default Home;

AI Update

I can see you're mixing React Router with Next.js data fetching patterns, which won't work as expected. Let me explain the issue and how to fix it.

The problem is that getServerSideProps is a Next.js-specific function that only works in the Next.js Pages Router. However, your code is using React Router (import { Link } from "react-router-dom"), which is a completely different routing system used in standard React applications (like Create React App or Vite).

These two approaches are incompatible - you can't use getServerSideProps in a React Router application.

Solutions

Option 1: Fetch Data in React (Keep React Router)

If you want to continue using React Router, fetch your Sanity data using standard React patterns:

import React, { useEffect, useState } from 'react';
import { Link } from "react-router-dom";
import Header from "../components/Header";
import "./Home.css";
import { Carousel, Card } from 'antd';
import { client } from "../lib/client";

const Home = () => {
  const [products, setProducts] = useState([]);
  const [bannerData, setBannerData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const productsQuery = `*[_type == "product"]`;
        const productsResult = await client.fetch(productsQuery);
        
        const bannerQuery = `*[_type == "banner"]`;
        const bannerResult = await client.fetch(bannerQuery);
        
        setProducts(productsResult);
        setBannerData(bannerResult);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <div>Loading...</div>;

  return (
    <div className="container">
      <Header/>
      <Carousel autoplay className="carousel">
        {bannerData?.map((e, index) => (
          <img key={index} src={e} className="carousel-img" alt="carousel" />
        ))}
      </Carousel>
      <div className="cards">
        <Card className="card">
          {products?.map((product) => (
            <div key={product.Slug}>
              <h1>{product.Name}</h1>
              <img src={product.Image} alt={product.Name} className="card-content"/>
              <br />
              <Link to="/categories" state={product.Genre} className="link">
                Shop Now
              </Link>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

export default Home;

Option 2: Switch to Next.js (Use getServerSideProps)

If you actually want to use Next.js for server-side rendering and SEO benefits, you'll need to migrate from React Router to Next.js. Your getServerSideProps code would then work, but you'd need to:

  1. Replace react-router-dom with Next.js's built-in routing
  2. Use Next.js <Link> component from next/link
  3. Place this file in the pages directory

Check out the Next.js Pages Router documentation for more details on how this works with Sanity.

Additional Notes

  • Your banner data appears to be returning raw values - you might need to use Sanity's image URL builder to properly construct image URLs
  • Consider adding error handling for failed data fetches
  • The key prop on your carousel items should be more specific than just the array index

The choice between React Router and Next.js depends on your project requirements - Next.js offers better SEO and server-side rendering, while React Router gives you more flexibility for client-side applications.

Hi there! Please keep your question and all relevant information in a single thread. This helps keep the channel clear and allows us to better keep track of your information. 🙂
It isn't displaying anything. I am mapping the returned prop but it displays nothing. I have data on sanity
I am following a tutorial, trying sanity for first time. It works for the instructor but it isn't working for me
What do you get in your console if you add
console.log({ products, bannerData });
on line 10, like this:

const Home = ({products, bannerData}) => {
  console.log({ products, bannerData });
It returns undefined
Why is it returning undefined?Did I do a mistake in
getServerSideProps?
A few things to check:1. If you run those queries in the Vision plugin in your Studio do you get the expected data? If not, the issue is with the query.
2. If you are getting the data in Vision, do you have your client properly configured in your frontend? Have you added your frontend to your CORS origins?
I didn't add frontend to CORS Origins
I added frontend to CORS origins
What is Vision Plugin?
Vision allows you to query against your dataset inside of your Studio. You should see two options in the black bar at the top of the page: Desk &amp; Vision. If it's not there, you can install it by following these instructions.
Can i somehow put the fetching inside a useEffect hook?
Everything else seems to be working
maybe I am not getting data at frontend
If you
console.log({ products, bannerData });
in
getServerSideProps
does the data show up? My guess is the client is misconfigured but I would have expected an error in your terminal.
Data shows up now . Image still isn't showing
Can anyone paste image schema here
Looks like I messed up image schema
Thank everyone issue solved

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?