Reputation: 885
Full error:
Error: Error serializing
.b
returned fromgetStaticProps
in "/". Reason:object
("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.
I am trying to call one of my functions that retrieves some data from an API endpoint however when trying to pass this data to props I get an error. I am not exactly sure what I am doing wrong as the fetch call works if its within GetStaticProps but I want all my logic for fetch calls to exist within a separate js page to reduce redundancies, however when doing so this error is created.
export async function getStaticProps() {
let b = WordpressService.getPageByIdTest(50);
return {
props: {
b: b,
},
revalidate: 30
}
}
const WordpressService = {
async getPageByIdTest(id) {
const resIndexPage = await fetch(`${url}pages/${id}`);
const indexPageData = await resIndexPage.json();
return indexPageData;
}
}
Upvotes: 3
Views: 11626
Reputation: 13
It can be easily solved with the package "superjson". Effective and easy to use. https://www.npmjs.com/package/superjson
for me, I wanted to convert "QuerySnapshot" from firestore which has timestamps in it.
posts = (await getDocs(postQuery)).docs.map((postDoc) => {
return superjson.stringify(postDoc);
});
picture from: https://www.npmjs.com/package/superjson
Upvotes: 0
Reputation: 588
I was going over the latest version of nextjs and I did notice that the demo was odd when I ran it. Specifically, I got this error when running their example:
Error: Additional keys were returned from
getStaticProps
. Properties intended for your component must be nested under theprops
key, e.g.
export async function getSortedPostsData() {
// Instead of the file system,
// fetch post data from an external API endpoint
const res = await fetch('..')
return res.json()
}
This is not exactly your issue but assigning the props object via res.json() also caused the same error you are experiencing.
So, for me, using node 15 I changed my api call to:
export async function getStaticProps() {
const url = `https://my-url`
const result = await fetch(url)
return { props: {
result: await result.json()
}}
}
And this solved my problem. So Ivar's comment looks correct - await the result and then in my case I had to also await the json result from node-fetch so that the promises completed properly.
Upvotes: 7