1

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 [email protected]

Any idea what's going on?

2
  • 3
    While you're correct in saying the console.log(response.data) is logging the right thing, that's not what await getAllCategories() actually returns. That's because you're missing a return statement right before the axios call, i.e. return axios.get(...).then(...).catch(...). Otherwise that function simply returns undefined. Commented May 7, 2022 at 17:57
  • 1
    you're correct @juliomalves, that solved my issue. Please add your comment as an answer so I can mark it as the correct answer so it can be more visible to other people. Thanks Commented May 7, 2022 at 22:54

1 Answer 1

1

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 } }
}

EDIT

In this particular case it was not necessary to add const data = await res.json() because the request is made via axios, and in axios responses are already served as javascript object, so there's no need to parse.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi. I did what you suggested but am getting now: TypeError: Cannot read properties of undefined (reading 'json')
Right, because as mentioned @juliomalves you should add return right before the axios call in your getAllCategories function, otherwise the function doesn't return anything (that's probably why you're getting an undefined error).
yes, you guys are right, that was the issue. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.