Ali Ehyaie
Ali Ehyaie

Reputation: 1260

use axios in getStaticProps in next js

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 enter image description here

I would be very grateful if anyone could help me

Upvotes: 3

Views: 11872

Answers (3)

Ali Ehyaie
Ali Ehyaie

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

Alex Shani
Alex Shani

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

Rukshan Jayasekara
Rukshan Jayasekara

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

Related Questions