Reputation: 1260
i have a next project.in this project i used axios for send and recieved request data. but i have a problem when i use axios in getStaticProps function i get an error in my index.js page
this is my index.js
import axios from "axios";
const Home = (props) => {
console.log(props);
return <div>d</div>;
};
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
return {
props: {
data: res
}
};
}
export default Home;
and this is my index.js page in my browser
I would be very grateful if anyone could help me
Upvotes: 3
Views: 11872
Reputation: 1260
it worked
try {
const result = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const data = result.data;
return {
props: {
data: data
}
}
} catch (error) {
console.log(error);
}
Upvotes: 11
Reputation: 161
You should use res.data
. Next time, I recommend to use console.log(res)
and see the object that you receive
Upvotes: 3
Reputation: 1985
Add JSON.stringify when calling an asynchronous function that returns an object.
Try modifying the getStaticProps
function like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const stringRes = JSON.stringify(res);
return {
props: {
data: stringRes
}
};
}
OR
Use .text()
to convert the response data to text like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1').lean();
const textRes = await res.text();
return {
props: {
data: textRes
}
};
}
Upvotes: 0