👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Troubleshooting a blog build with React and Sanity, including CORS issues and missing images.

23 replies
Last updated: Jul 13, 2021
Hello, I'm following this step https://www.sanity.io/guides/build-your-first-blog-using-react and my output is in the screen shot. There is a blog, author, and tag already created. It is not posting on the localhost:3000.
The projectId and dataset has been entered in already.
Jul 13, 2021, 6:03 PM
Hello Geoff, that is the results at the end of the guide
Jul 13, 2021, 6:05 PM
At this part of the guide, it goes over CORS Origins. You’ll want to add
<http://localhost:3000>
(ensure it’s
http
and not
https
).
Jul 13, 2021, 6:08 PM
it's http://
Jul 13, 2021, 6:08 PM
vsc is showing
Jul 13, 2021, 6:09 PM
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import sanityClient from "../client.js";

export default function AllPosts() {
  const [allPostsData, setAllPosts] = useState(null);

  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "post"]{
        title,
        slug,
        mainImage{
        asset->{
          _id,
          url
        }
      }
    }`
      )
      .then((data) => setAllPosts(data))
      .catch(console.error);
  }, []);

  return (
    <div className="bg-green-100 min-h-screen p-12">
      <div className="container mx-auto">
        <h2 className="text-5xl flex justify-center cursive">Blog Posts</h2>
        <h3 className="text-lg text-gray-600 flex justify-center mb-12">
          Welcome to my blog posts page!
        </h3>
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
          {allPostsData &&
            allPostsData.map((post, index) => (
              <Link to={"/" + post.slug.current} key={post.slug.current}>
                <span
                  className="block h-64 relative rounded shadow leading-snug bg-white
                      border-l-8 border-green-400"
                  key={index}
                >
                  <img
                    className="w-full h-full rounded-r object-cover absolute"
                    src={post.mainImage.asset.url}
                    alt=""
                  />
                  <span
                    className="block relative h-full flex justify-end items-end pr
                      -4 pb-4"
                  >
                    <h2
                      className="text-gray-800 text-lg font-bold px-3 py-4 bg-red-700
                        text-red-100 bg-opacity-75 rounded"
                    >
                      {post.title}
                    </h2>
                  </span>
                </span>
              </Link>
            ))}
        </div>
      </div>
    </div>
  );
}
Jul 13, 2021, 6:12 PM
App.js
import React from "react";
import { BrowserRouter, Route } from "react-router-dom";
import AllPosts from "./Components/AllPosts.js";
import OnePost from "./Components/OnePost.js";

function App() {
  return (
    <BrowserRouter>
      <div>
        <Route component={AllPosts} path="/" exact />
        <Route component={OnePost} path="/:slug" />
      </div>
    </BrowserRouter>
  );
}
export default App;
src/Components/OnePost.js

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import sanityClient from "../client.js";
import BlockContent from "@sanity/block-content-to-react";
import imageUrlBuilder from "@sanity/image-url";

const builder = imageUrlBuilder(sanityClient);
function urlFor(source) {
  return builder.image(source);
}

export default function OnePost() {
  const [postData, setPostData] = useState(null);
  const { slug } = useParams();

  useEffect(() => {
    sanityClient
      .fetch(
        `*[slug.current == "${slug}"]{
           title,
           slug,
           mainImage{
           asset->{
              _id,
              url
            }
          },
          body,
          "name": author->name,
          "authorImage": author->image
       }`
      )
      .then((data) => setPostData(data[0]))
      .catch(console.error);
  }, [slug]);

  if (!postData) return <div>Loading...</div>;

  return (
    <div className="bg-gray-200 min-h-screen p-12">
      <div className="container shadow-lg mx-auto bg-green-100 rounded-lg">
        <div className="relative">
          <div className="absolute h-full w-full flex items-center justify-center p-8">
            {/* Title Section */}
            <div className="bg-white bg-opacity-75 rounded p-12">
              <h2 className="cursive text-3xl lg:text-6xl mb-4">
                {postData.title}
              </h2>
              <div className="flex justify-center text-gray-800">
                <img
                  src={urlFor(postData.authorImage).url()}
                  className="w-10 h-10 rounded-full"
                  alt="Author is Kap"
                />
                <h4 className="cursive flex items-center pl-2 text-2xl">
                  {postData.name}
                </h4>
              </div>
            </div>
          </div>
          <img
            className="w-full object-cover rounded-t"
            src={urlFor(postData.mainImage).url()}
            alt=""
            style={{ height: "400px" }}
          />
        </div>
        <div className="px-16 lg:px-48 py-12 lg:py-20 prose lg:prose-xl max-w-full">
          <BlockContent
            blocks={postData.body}
            projectId={sanityClient.clientConfig.projectId}
            dataset={sanityClient.clientConfig.dataset}
          />
        </div>
      </div>
    </div>
  );
}
src/Components/AllPost.js

Jul 13, 2021, 6:12 PM
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import sanityClient from "../client.js";

export default function AllPosts() {
  const [allPostsData, setAllPosts] = useState(null);

  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "post"]{
        title,
        slug,
        mainImage{
        asset->{
          _id,
          url
        }
      }
    }`
      )
      .then((data) => setAllPosts(data))
      .catch(console.error);
  }, []);

  return (
    <div className="bg-green-100 min-h-screen p-12">
      <div className="container mx-auto">
        <h2 className="text-5xl flex justify-center cursive">Blog Posts</h2>
        <h3 className="text-lg text-gray-600 flex justify-center mb-12">
          Welcome to my blog posts page!
        </h3>
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
          {allPostsData &&
            allPostsData.map((post, index) => (
              <Link to={"/" + post.slug.current} key={post.slug.current}>
                <span
                  className="block h-64 relative rounded shadow leading-snug bg-white
                      border-l-8 border-green-400"
                  key={index}
                >
                  <img
                    className="w-full h-full rounded-r object-cover absolute"
                    src={post.mainImage.asset.url}
                    alt=""
                  />
                  <span
                    className="block relative h-full flex justify-end items-end pr
                      -4 pb-4"
                  >
                    <h2
                      className="text-gray-800 text-lg font-bold px-3 py-4 bg-red-700
                        text-red-100 bg-opacity-75 rounded"
                    >
                      {post.title}
                    </h2>
                  </span>
                </span>
              </Link>
            ))}
        </div>
      </div>
    </div>
  );
}
Jul 13, 2021, 6:12 PM
If you go to http://localhost:3000/testing , does that work?
Also, just to confirm, did you name the file AllPost.js or AllPosts.js?
Jul 13, 2021, 6:25 PM
I apologize for my typeo it's AllPosts.js
Jul 13, 2021, 6:27 PM
when I go to /testing it is showing loading...
Jul 13, 2021, 6:29 PM
Okay. It seems like we’re never getting anything back from the query. That could be several things—including a CORS issue—so just to be positive could you run
sanity cors list
from your sanity folder in your terminal?
Jul 13, 2021, 6:41 PM
Is port 3000 also there?
Jul 13, 2021, 6:43 PM
localhost:3333 will be your Sanity studio. Your front end will run on port 3000 at http://localhost:3000 .
Jul 13, 2021, 6:43 PM
If you type
sanity cors add <http://localhost:3000>
then choose
no
, you can try your site again in the browser.
Jul 13, 2021, 6:44 PM
Yes, there is 3000 and 3333
Jul 13, 2021, 6:57 PM
Yes, there is 3000 and 3333
Jul 13, 2021, 6:57 PM
Yes, there is 3000 and 3333
Jul 13, 2021, 6:57 PM
the problem is it required img

                  {/*<img
                    className="w-full h-full rounded-r object-cover absolute"
                    src={post.mainImage.asset.url}
                    alt=""
                  />*/}
Jul 13, 2021, 7:01 PM
That error is appearing because there’s no
mainImage
. If you add one to your post, it should go away. You probably also want to check that
mainImage
exists before rendering it out (like you did with
{allPostsData && ...


Yes, there is 3000 and 3333
Interesting. I’m afraid I don’t know what the problem is then.
Jul 13, 2021, 7:01 PM
Now it is working
Jul 13, 2021, 7:01 PM
What you told me to do with CORS has fixed it 🙂
Jul 13, 2021, 7:01 PM
Thank you
Jul 13, 2021, 7:01 PM
Great! Glad to hear it Terry. Have fun building!
Jul 13, 2021, 7:01 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?