I'm working with Next.js trying to getServerSIdeProps and and getting this error:
Error: Error serializing
.resultsreturned fromgetServerSidePropsin "/". Reason:undefinedcannot be serialized as JSON. Please usenullor omit this value.
export async function getServerSideProps(context) {
const genre = context.query.genre;
const request = await fetch(
`https://api.themoviedb.org/3${
requests[genre]?.url || requests.fetchTrending.url
}`
).then((res) => res.json());
return {
props: {
results: request.results,
},
};
}
It was working yesterday but today I'm getting this error. Could any body please help me?
while converting your data to JSON an error was thrown because the value undefined can not be serialized in other words you can't turn objects with undefined as the value of one of their properties to json.
You need to turn the undefined value to null value for javascript to be able to serialize it to JSON(convert it to JSON).
The easiest way to turn undefined values to null in javascript is using a library called Lodash. Install Lodash using the commands below:
$ npm install lodash
// or
$ yarn add lodash
After that create the functions below:
import _ from 'lodash';
function prepareForSerializatoin(obj) {
return obj.mapValues(obj, value => typeof value === 'undefined' ? null : value);
}
Finally, use this function while returning your response:
export async function getServerSideProps(context) {
const genre = context.query.genre;
const request = await fetch(
`https://api.themoviedb.org/3${
requests[genre]?.url || requests.fetchTrending.url
}`
).then((res) => res.json());
return prepareForSerializatoin({
props: {
results: request.results,
},
});
}