Promise example
nextjsHere’s an example of using Promises to make an API call in a Next.js server-side function:
import fetch from 'isomorphic-unfetch'
export default function getData() {
return new Promise((resolve, reject) => {
fetch('https://my-api.com/endpoint')
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error))
})
}
You can then call this function in a page component like this:
import getData from '../lib/getData'
function MyPage(props) {
return (
<div>
{props.data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
)
}
MyPage.getInitialProps = async function() {
try {
const data = await getData()
return { data }
} catch (error) {
return { error }
}
}
If the getData function resolves with the data from the API, it will be passed to the page component as a prop. If the function rejects with an error, it will be caught in the catch block and you can handle the error as needed.
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