NextJS: Error serializing `.data.data` returned from `getServerSideProps`

I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use getServerSideProps to get data from the server on load, so I've got the following:

myProject/pages/category/new.js:

export default function AddNewCategory(data) {
...
}

export const getServerSideProps = async () => {
    const data = await getAllCategories();
    console.log(await data)
    return {
        props: {
            data: { data }
        }
    };
};

myProject/api/category.js:

import axios from "axios";

// getAllCategories returns a list of all active categories
export const getAllCategories = async() => {

    axios.get("http://127.0.0.1:8080/api/v1/categories")
        .then(function (response) {
            console.log(response.data)
            return response.data;
        })
        .catch(error => {
            console.error("error")
            console.log(error)
        })

}

As you can see I've got a print statement in getAllCategories which prints:

{
  data: [
    {
      id: 1,
      name: 'Pop',
      slug: 'pop',
      description: 'Pop',
      parent: 0,
      active: true,
      created_at: '2022-05-03T19:50:00-04:00',
      updated_at: '2022-05-03T19:50:00-04:00',
      deleted_at: null
    },
    {
      id: 3,
      name: 'Pop 2',
      slug: 'pop-2',
      description: 'Pop',
      parent: 0,
      active: true,
      created_at: '2022-05-03T19:50:24-04:00',
      updated_at: '2022-05-03T19:50:24-04:00',
      deleted_at: null
    }
  ]
}

yet I'm getting the following error:

error - Error: Error serializing .data.data returned from getServerSideProps in "/category/new". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

I saw around that I should try to convert the data to string and then back to json:

return { 
  props: { 
    data: JSON.parse(JSON.stringify(data)) 
  } 
};

but when I do this I'm getting a different error:

error - SyntaxError: Unexpected token u in JSON at position 0

I'm using next@12.1.5

Any idea what's going on?

1 answer

  • answered 2022-05-07 07:11 paulin-crtn

    I believe you have to convert your json to a javascript object with .json(). The following code comes from nextjs documentation.

    export async function getServerSideProps() {
      // Fetch data from external API
      const res = await getAllCategories();
      const data = await res.json()
    
      // Pass data to the page via props
      return { props: { data } }
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum