next-js fetch data from api

เรามักจะ fetch ใน getStaticProps หรือใน getServerSideProps เราไปดูตัวอย่างกัน

ตัวอย่างโค้ด

import fetch from 'isomorphic-unfetch'

export async function getStaticProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts')
    const data = await res.json()
    return {
        props: {
            data
        }
    }
}

เรายังสามารถใช้ axios ได้ตามตัวอย่าง

import axios from 'axios'

export async function getStaticProps() {
    const res = await axios.get('https://jsonplaceholder.typicode.com/posts')
    const data = res.data
    return {
        props: {
            data
        }
    }
}


Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com