How to fetch "date published" and "category" in a React blog using Sanity.io.

9 replies
Last updated: Sep 13, 2021
Hi. Who has an idea on how to fetch for an article "date published" and "category" while doing a fetch, this is in React blog and Sanity
AI Update

To fetch "date published" and "category" fields for blog articles in a React app with Sanity, you'll use the Sanity Client with a GROQ query that specifies exactly which fields you want to retrieve.

Basic Setup

First, install and configure the Sanity Client:

npm install @sanity/client

Then create a client instance:

import { createClient } from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'production',
  useCdn: true, // set to false for fresh data
  apiVersion: '2024-01-01', // use current date
})

Fetching Articles with Specific Fields

Use a GROQ query to fetch your blog posts with the publishedAt (or whatever you named your date field) and category fields:

import { useEffect, useState } from 'react'

function BlogList() {
  const [articles, setArticles] = useState([])

  useEffect(() => {
    const query = `*[_type == "post"] {
      _id,
      title,
      slug,
      publishedAt,
      category->{
        _id,
        title
      }
    }`

    client.fetch(query)
      .then(data => setArticles(data))
      .catch(console.error)
  }, [])

  return (
    <div>
      {articles.map(article => (
        <article key={article._id}>
          <h2>{article.title}</h2>
          <p>Published: {new Date(article.publishedAt).toLocaleDateString()}</p>
          <p>Category: {article.category?.title}</p>
        </article>
      ))}
    </div>
  )
}

Key Points

  • Field names: Use the exact field names from your schema (publishedAt, datePublished, etc.)
  • Reference expansion: The category->{...} syntax expands referenced documents. If category is just a string field, use category directly without the arrow
  • Filtering: Add filters like *[_type == "post" && defined(publishedAt)] to only get published articles
  • Sorting: Add | order(publishedAt desc) at the end of your query to sort by date

If you're using Next.js specifically, consider using sanityFetch from next-sanity which provides better caching and revalidation options for server components and API routes.

useEffect(() =&gt; { sanityClient
.fetch(

*[_type == "post"]{
        title,
        slug,
        date,
        mainImage{
          asset->{
          _id,
          url
        }
      }
    }
)
.then((data) =&gt; setAllPosts(data))
.catch(console.error);
}, []);
that's what i got,how do I fetch the date and the category as well ?
There are a few options, you would have to add the names of the fields to the query's projection or you could add an ellipsis to the projection (
...,
) to get the remaining fields without having to name them.
Kindly show me how by just adding it to the code snippet I've sent. Thank you.
Kindly show me how by just adding it to the code snippet I've sent. Thank you.
I don't know the names of your fields in your schema, but adding the ellipsis would look like this:
useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "post"]{
        ...,
        title,
        slug,
        date,
        mainImage{
          asset->{
          _id,
          url
        }
      }
    }`
      )
      .then((data) => setAllPosts(data))
      .catch(console.error);
  }, []);
Thanks,I'll update my working. Then one last question how will i know the exact names that i should use? For example for the date and category ?
You would have to take a look at what you added to the 'name' property of those fields you created in your schema. If this is the guide you're using (or if you're following along with Kap's video on Youtube) it's likely that they're called 'categories' and 'publishedAt'.
So it would probably be something like:

useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "post"]{
        title,
        slug,
        date,
        mainImage{
          asset->{
            _id,
            url
          }
        },
        publishedAt,
        categories[]->
    }`
      )
      .then((data) => setAllPosts(data))
      .catch(console.error);
  }, []);
Thank you.πŸ™

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?