How to fetch "date published" and "category" in a React blog using Sanity.io.
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/clientThen 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, usecategorydirectly 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.
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.