Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: How to serialize data from getStaticProps : Next.js

I'm working with Next.js, I tried accessing data but got this error:

Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

My code:

import { getAllBusinessProfiles } from '../../lib/api';

const Profile = ({ allProfiles: { edges } }) => {
    return ( 
        <>
          <Head>
            <title>Profile</title>
          </Head>

          <Hero />

          <section>
            {edges.map(({ node }) => (
              <div key={node.id}>
                  <Link href={`/profile/${node.slug}`}>
                    <a> {node.businessInfo.name} </a>
                  </Link>
              </div>
            ))}
          </section>

        </>
     );
}
 
export default Profile;

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }

getAllBusinessProfiles from api.js:

const API_URL = process.env.WP_API_URL;

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' };

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables })
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getAllBusinessProfiles() {
    const data = await fetchAPI(
      `
      query AllProfiles {
        businessProfiles(where: {orderby: {field: DATE, order: ASC}}) {
          edges {
            node {
              date
              title
              slug
              link
              uri
              businessInfo {
                name
                title
                company
                image {
                  mediaItemUrl
                  altText
                }
                highlight
                phone
                city
                country
                facebook
                instagram
                email
                website
                profiles {
                  profile
                  profileInfo
                }
                extendedProfile {
                  title
                  info
                }
              }
            }
          }
        }
      }
      
      `
    );
    return data?.businessProfiles;
};

What could be the error here? I used the getStaticProps method on Next.js but got the error above instead. Please, check. Thanks.

The error: Server Error Error: Error serializing .profileData returned from getStaticProps in "/profile/[slug]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

I don't know what could cause this though.

like image 866
Adewale Perfect Avatar asked Feb 08 '21 17:02

Adewale Perfect


People also ask

Why can't I serialize the profile data returned from getstaticprops?

The error: Server Error Error: Error serializing .profileData returned from getStaticProps in "/profile/ [slug]". Reason: undefined cannot be serialized as JSON.

What is the difference between getstaticprops and getserversideprops?

getStaticProps (Static Generation): Fetch data at build time. getStaticPaths (Static Generation): Specify dynamic routes to pre-render pages based on data. getServerSideProps (Server-side Rendering): Fetch data on each request. In addition, we’ll talk briefly about how to fetch data on the client side.

How do I use getstaticprops with next?

When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps. This JSON file will be used in client-side routing through next/link or next/router.

What is the difference between unstable_revalidate and getstaticprops?

getStaticProps runs in the background when using revalidate getStaticProps runs on-demand in the background when using unstable_revalidate When combined with Incremental Static Regeneration, getStaticProps will run in the background while the stale page is being revalidated, and the fresh page served to the browser.


2 Answers

Add JSON.stringify when calling an asynchronous function that returns an object.

Try modifying your getStaticProps function like this.

export async function getStaticProps() {
    const profiles = await getAllBusinessProfiles();
    const allProfiles = JSON.stringify(profiles)

    return {
        props: {
             allProfiles
        }
   };
}

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Source: MDN

like image 141
Fernando Avatar answered Sep 23 '22 09:09

Fernando


I had the same issue when I was working with redux with next js and the reason was one of the fields in the default state I set it to undefined. Instead I used null:

const INITIAL_STATE = {
  products: [],
  loading: false,
  error: undefined,
  cart: [],
};

error:undefined was causing the error. Because "undefined" cannot be serialized:

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }

you are returning "allProfiles" which is the result of async getAllBusinessProfiles() which is either returning undefined, error or one of the fields of the returned object is undefined. "error" object is not serializable in javascript

like image 27
Yilmaz Avatar answered Sep 20 '22 09:09

Yilmaz