👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Trouble fetching data of multiple document types in NextJS with Sanity

7 replies
Last updated: Apr 2, 2022
Hello, I am using NextJS with Sanity and trying to fetch data of more than one document type to render on a page. I’m trying to use the below query but at the moment it is not working. Specifically I have a page on my website for events, and on that page I want to fetch ‘calendar’ documents, ‘notice’ documents, and ‘event’ documents.
*[_type in ['event', 'calendar', 'notice']]{
_type == 'event': {
  eventTitle,
  eventDate,
  venue,
  mainImage,
  artists[]->,
},
_type == 'notice': {
  _id,
  title,
  body, 
},
_type == 'calendar': {
  _id,
  month,
  'event': event[]->{
  title[],
  date,
  },
},
}
Grateful for any tips!
🙏
Apr 2, 2022, 4:43 PM
Ok so changing the
:
to a
=>
made it work 🙂
*[_type in ['event', 'calendar', 'notice']]{
_type == 'event' => {
  eventTitle,
  eventDate,
  venue,
  mainImage,
  artists[]->,
},
_type == 'notice' => {
  _id,
  title,
  body, 
},
_type == 'calendar' => {
  _id,
  month,
  'event': event[]->{
  title[],
  date,
  },
},
}
Apr 2, 2022, 4:54 PM
Glad you got it working! 🙌
Apr 2, 2022, 4:56 PM
Ok so changing the
:
to a
=>
made it work 🙂
*[_type in ['event', 'calendar', 'notice']]{
_type == 'event' => {
  eventTitle,
  eventDate,
  venue,
  mainImage,
  artists[]->,
},
_type == 'notice' => {
  _id,
  title,
  body, 
},
_type == 'calendar' => {
  _id,
  month,
  'event': event[]->{
  title[],
  date,
  },
},
}
Apr 2, 2022, 4:54 PM
Thanks
user A
:)
Apr 2, 2022, 5:31 PM
Would you have any tips on why I am now having trouble using map() to fetch the calendar part of my eventsUpcoming query for a component now?
{eventsUpcoming.calendar.map((calendar) => (
   <IndexCal
    key={calendar._id}
    heading={calendar.month}
    event={calendar.event}
    />
))}
Apr 2, 2022, 5:33 PM
Would you have any tips on why I am now having trouble using map() to fetch parts of this query for a component now?
{eventsUpcoming.calendar.map((calendar) => (
   <IndexCal
    key={calendar._id}
    heading={calendar.month}
    event={calendar.event}
    />
))}
Apr 2, 2022, 5:33 PM
This is my getServerSideProps:
export const getServerSideProps = async () => {
const eventsUpcoming = await sanityClient.fetch(eventsUpcomingQuery);
  return {
    props: {
      eventsUpcoming,
    },
  };
};
Apr 2, 2022, 5:37 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.

Was this answer helpful?