Query Sanity Content with GROQ to Return a List of Posts

Ben Patton
InstructorBen Patton
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated a year ago

In this lesson, we use Sanity's Vision feature that provides us with a playground editor to use Sanity's GROQ query language to interact and get specific data from our CMS.

GROQ affords us the ability to query our CMS data in the specific format that we want.

If you want a deeper dive into the GROQ query language, check out this free course on egghead from John Lindquist

Instructor: [0:00] Now that we've added this markdown, we can come back up in here and just go ahead and spend some time and create one post, and then we create a second post. Next, we can come into our dashboard and click Vision. This will give us a query playground where we can work on writing our GROQ queries to get our post data.

[0:18] To get a list of our posts, we can come in and give the star, the array syntax, and say _type = post. This will give us everything in our CMS where the type is equal to post. Fetch, and I'll get two posts.

[0:35] Now we want to get specific properties off post. From when we created our schema, I know that I want to get Title, the slug, and I set that equal to a string, because the slug is an object that has a property called current, which is the string that we want.

[0:51] We want to get the Author, the Author is an object, and we want to get the Name. Then we want to get Published At. We actually list that Published At to the string Date, and then we want to get the Body and then we want Categories.

[1:07] If we fetch that, we got most everything we wanted. This Categories is an array, we can access the array and use the arrow syntax again. Categories has the title, so then we just want to use the object brackets again, and get the Title. We can fetch that, and so we're getting our Author, Body, Categories, Date, Slogan, Title.

[1:32] This is getting a list of posts, but in the future, we know that we will want to get a single post. If we come into here and grab the slug, we can come back into our query. The way that you can get a specific post information is to say, [inaudible] nn slug.current equals, and then you can give it a string and it will only return the information for that specific post.

[1:56] All right, so we're only getting the single post back.

[1:58] In review, in this lesson, we use the GROQ query language to query our Sanity CMS and get a list of posts and a single post. If you want a deeper dive into the GROQ query language, Egghead has a free course by John Lindquist, which is short and gets you up to speed pretty quickly.