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.datareturned fromgetServerSidePropsin "/category/new". Reason:undefinedcannot be serialized as JSON. Please usenullor 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?
console.log(response.data)is logging the right thing, that's not whatawait getAllCategories()actually returns. That's because you're missing a return statement right before theaxioscall, i.e.return axios.get(...).then(...).catch(...). Otherwise that function simply returnsundefined.