nextjs fetch api example
nextjsHere’s an example of using the fetch API in a Next.js page:
import { useState, useEffect } from 'react'
function Example() {
const [data, setData] = useState(null)
useEffect(() => {
async function fetchData() {
const res = await fetch('/api/example')
const json = await res.json()
setData(json)
}
fetchData()
}, [])
if (!data) {
return <div>Loading...</div>
}
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
)
}
export default Example
This example fetches data from an API endpoint at /api/example when the component is mounted. The response is awaited and then the JSON data is saved to the data state variable using the setData function. The component renders a loading message until the data is available, at which point it renders a list of items.
Other Article on Tag nextjs
- - fetch function mode sors, no-cors, same-origin
- - fetch request option
- - How to add Bootstrap in Next.js
- - how to minimize front in next js
- - nextjs add bootstrap
- - nextjs add Font Awesome
- - nextjs add font face in head
- - nextjs add prismjs
- - nextjs add Syntax highlighting code
- - nextjs call api