How to fetch "date published" and "category" in a React blog using Sanity.io.
9 replies
Last updated: Sep 13, 2021
O
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
Sep 13, 2021, 9:34 AM
O
useEffect(() => { sanityClient
.fetch(
)
.then((data) => setAllPosts(data))
.catch(console.error);
}, []);
.fetch(
*[_type == "post"]{ title, slug, date, mainImage{ asset->{ _id, url } } }
.then((data) => setAllPosts(data))
.catch(console.error);
}, []);
Sep 13, 2021, 4:43 PM
O
that's what i got,how do I fetch the date and the category as well ?
Sep 13, 2021, 4:44 PM
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.
Sep 13, 2021, 4:47 PM
O
Kindly show me how by just adding it to the code snippet I've sent. Thank you.
Sep 13, 2021, 4:48 PM
O
Kindly show me how by just adding it to the code snippet I've sent. Thank you.
Sep 13, 2021, 4:48 PM
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); }, []);
Sep 13, 2021, 5:02 PM
O
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 ?
Sep 13, 2021, 5:05 PM
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:
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); }, []);
Sep 13, 2021, 5:10 PM
O
Thank you.š
Sep 13, 2021, 5:12 PM
Sanityā build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.