Fetch article date and category in React with Sanity

9 replies
Last updated: Nov 29, 2025
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.

Show original thread
9 replies

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?