Fetching data from multiple documents in NextJS and resolving errors
7 replies
Last updated: Jan 10, 2022
Hi All, I’m trying to fetch data with more than 1 query I found this answer and am referencing that answer. my query looks like this
When I start up the Next app, I’m getting this error
Is there a better way to fetch data from more than 1 document with NextJS?
export const frontPageSettings = ` *[_id in ["frontpage", "siteSettings"]]{ _id == "frontpage" => { _id, pageDescription, pageTitle, pageBuilder, mainImage }, _id == "siteSettings" => { title, description, primaryColor, secondaryColor, keywords } } `
error - ClientError: expected '}' following object body
Jan 10, 2022, 9:39 PM
follow up question to this, when I fetch data like this, it returns a lot of my fields as arrays that just read
[[object], [object]]and it seems like it can’t actually read those objects, how would I go about this?
Jan 10, 2022, 9:59 PM
That usually means that you're using a promise-based value that hasn't resolved yet. Did you maybe forget an
awaitsomewhere?
Jan 10, 2022, 10:01 PM
I don’t think so, my getServerSideProps has the
awaitin it. For reference this also happened when I was fetching a _type without specifying index 0 or
[0]after my type call
Jan 10, 2022, 10:03 PM
export const getServerSideProps = async function (context) { const data = await client.fetch(frontPageSettings) return { props: { data }, } }
Jan 10, 2022, 10:05 PM
Here’s my getServerSideProps
Here’s my page component
And this is what my console is logging
export const getServerSideProps = async function (context) { const data = await client.fetch(frontPageSettings) return { props: { data }, } }
export default function Home({ data }) { console.log(data) return ( <></> ) }
[ { _id: 'frontpage', mainImage: { _type: 'image', asset: [Object] }, pageBuilder: [ [Object], [Object], [Object], [Object] ], pageDescription: [ [Object] ], pageTitle: 'Frontpage' }, ]
Jan 10, 2022, 10:06 PM
Your server/terminal console is not going to drill down into objects, but you can “expand” those objects using something like this:
As for using that data on your page, you’ll need to specify keys on objects (e.g., if
You’ll probably want to render
console.log(JSON.stringify(data, null, 2))
personis an object, you can’t use that on the page—you’d need to specify
person.name, as an example) and map through arrays (e.g., if
peopleis an array, you’ll need to map through it and handle each
person). Both of those are seen here, where
categoriesis an array and each
categoryis an object with at least
_idand
titlekeys on it:
<ul> {categories.map(category => ( <li key={category._id}>{category.title}</li> ))} </ul>
categoriesconditionally (check if it’s empty and if it is, don’t try to map over it).
Jan 10, 2022, 11:59 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.