See Sanity in action 👀 Join us for a live product demo + Q&A →

Query for posts not working on Next frontend, likely issue with startOfMonth() function

4 replies
Last updated: Feb 28, 2023
Hey team!I'm using this query:


*[_type == "post" && _createdAt >= "${startOfMonth(
        new Date()
    )}"] | order(_createdAt desc) {
      title,
      description,
      "mainImage": mainImage.asset->url,
      "slug": slug.current
    }
which is returning posts properly in my VIsion tab but not on my Next frontend. Can you see any problems with it? (i am importing startOfMonth properly, i think,
import { formatISO, startOfMonth } from "date-fns";
)
Feb 28, 2023, 9:33 AM
You’re authenticated in the Studio when running queries with Vision, which you might not be in your Next app.
Are you using a private dataset? Or trying to query for drafts? Your client would need a token in this cases.
Feb 28, 2023, 10:19 AM
Hi Simeon, thank you for your answer! I am authenticated on my Next, i can fetch posts and even drafts (i have a valid read token). If i do
*[_type == "post"]
for instance i can fetch posts. Could it be something to do with the startOfMonth() ? if i
console.log(startOfMonth(new Date()));
i get a 2023-02-01T0000.000Z, it should be fine right?
Feb 28, 2023, 10:56 AM
It’s likely something with your function.
It might be easier to debug if you use a variable. So in GROQ write $startOfMonth and then in your query params return a string value of the date.
Feb 28, 2023, 11:42 AM
Thank you! I managed to get it to work like this:

import { formatISO, startOfMonth } from "date-fns";

const now = new Date();
const startOfMonthString = formatISO(startOfMonth(now));
const params = { startOfMonth: startOfMonthString };



const query = groq`
    *[_type == "post" && _createdAt >= $startOfMonth] {
      title,
      description,
      "mainImage": mainImage.asset->url, 
      "slug": slug.current,
    }
  `;

const posts: Post[] = await client.fetch(query, params);
Feb 28, 2023, 5:18 PM

Sanity.io – build remarkable experiences at scale

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

Categorized in