Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Troubleshooting creating a button to link to the most recent blog using Next.js and Sanity.io API.

23 replies
Last updated: Nov 23, 2021
Is there a way I can create a button that would take me to index 0 of my blog, for instance I would want this button to always link to the most recent blog
Nov 23, 2021, 9:59 PM
okay so I'm trying to have this button live in my navbar so my nav component file has the getServerSideProps of
export const getServerSideProps = async pageContext => {
    const query = encodeURIComponent('*[_type == "post"][0]');
    const url = `<https://cd0q2c94.api.sanity.io/v1/data/query/production?query=${query}>`;
    const result = await fetch(url).then(res => res.json());

    if (!result.result || !result.result.length) {
        return {
            props: {
                post: [],
            }
        }
    } else {
        return {
            props: {
                post: result.slug,
            }
        }
    }
}
Nov 23, 2021, 10:30 PM
and its returning undefined
Nov 23, 2021, 10:30 PM
Hm, a few thoughts here. You're using
v1
of the API, which could be causing some issues for you. Second, are you using Next? If so, the method you're using for querying your content here isn't your best option. You'd probably have an easier go of it if you use the next-sanity package.
Nov 23, 2021, 10:35 PM
ooh the tutorial I learned from must be outdated
Nov 23, 2021, 10:36 PM
yes i am using next
Nov 23, 2021, 10:36 PM
So now that I have that installed is there an easy way to achieve this?
Nov 23, 2021, 10:40 PM
Got it! Yeah, I would recommend making the switch to that package. It's fairly straightforward. First install the package, then set up the following:
/lib/sanity.js

import {createClient} from 'next-sanity'

const config = {
  dataset: <your-dataset-name>,
  projectId:<your-project-id>,
  apiVersion: '2021-10-21',
  useCdn: process.env.NODE_ENV === 'production'
}

export const sanityClient = createClient(config)

export const PortableText = createPortableTextComponent({
  ...config,
  serializers: {},
})
This file does a few things: it configures a client that you can use for querying and sets up a Portable Text component for serializing rich text.

Then, in your
getServerSideProps
we can change it to the following:
import { sanityClient } from './lib/sanity.js'

//other code

export const getServerSideProps = async pageContext => {
    const query = '*[_type == "post"][0]';
    const result = sanityClient.fetch(query)

    if (!result.length) {
        return {
            props: {
                post: [],
            }
        }
    } else {
        return {
            props: {
                post: result.slug,
            }
        }
    }
}
Nov 23, 2021, 10:48 PM
hmm is lib a folder that already exists or do I have to create? because I'm getting this
Nov 23, 2021, 10:58 PM
Ah, you would have to add
createPortableTextComponent
to your import from next-sanity. I left that out. It should look like this:
import { createClient, createPortableTextComponent } from next-sanity
Nov 23, 2021, 11:00 PM
And yes,
lib
is a directory that you would need to make to store your
sanity.js
file.
Nov 23, 2021, 11:01 PM
Okay so the { post } that I'm passing into my component from the props is still returning undefined, should I be passing it in another way?
Nov 23, 2021, 11:06 PM
I'm thinking it has something to do with me error handler
if (!result.length) {
        return {
            props: {
                post: [],
            }
        }
    }
Nov 23, 2021, 11:08 PM
beacuse its looking for an array but should be just 1 slug
Nov 23, 2021, 11:08 PM
try removing the
.length
Nov 23, 2021, 11:08 PM
That didnt do it, here's my component code
const Navbar = ({ post }) => {
    console.log(post)
    return ( 
        <nav className={styles.nav}>
            <ul className={styles.navList}>
                    <Link href="/">
                        <li className={styles.navItem}>
                            <a>Home</a>
                        </li>
                    </Link>
                    <Link href="/about">
                        <li className={styles.navItem}>
                            <a>About</a>
                        </li>
                    </Link>
                    <Link href={post}>
                        <li className={styles.navItem}>
                            <a>Blog</a>
                        </li>
                    </Link>
            </ul>
        </nav>
     );
}
Nov 23, 2021, 11:10 PM
I don't think it's that component that's causing the issue. Can you share how you configured your client? Have you added your frontend to your CORS origins?
Nov 23, 2021, 11:12 PM
I haven't done anything with cors, I created the next project with npx create-next-app and am making the api calls to sanity
Nov 23, 2021, 11:14 PM
You'll need to add the domain that you're currently using for your frontend to your CORS origins on manage.sanity.io . That's likely one of the reasons your queries aren't returning results. Did you add the correct projectID and dataset name to your client configuration as well?
Nov 23, 2021, 11:16 PM
I haveny deployed my next app yet, this is just local host
Nov 23, 2021, 11:16 PM
You still need to add a CORS origin
Nov 23, 2021, 11:17 PM
okay I added http://localhost:3000 to my CORS origin
Nov 23, 2021, 11:19 PM
I'm gettingError: Failed prop type: The prop
href
expects a
string
or
object
in
<Link>
, but got
undefined
instead.null
Nov 23, 2021, 11:20 PM
when I remove that from the Link, and try console logging it , It still sends undefined
Nov 23, 2021, 11:24 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?