how to fetch data from api in next js 14

preview_player
Показать описание

prerequisites

make sure you have the following before you start:

```bash
cd my-next-app
```

3. **api**: you’ll need an api to fetch data from. for demonstration, we can use a public api like jsonplaceholder or any other restful api.

1. using server-side rendering (ssr)

ssr allows you to fetch data on each request. this is useful for pages that need to display dynamic content.

**example**: fetching data from jsonplaceholder

```javascript

import react from 'react';

const posts = ({ posts }) = {
return (
div
h1posts/h1
ul
/li
))}
/ul
/div
);
};

export async function getserversideprops() {

return {
props: {
posts,
},
};
}

export default posts;
```

in this example:
- the `getserversideprops` function fetches data from the api and passes it as props to the `posts` component.
- the data will be fetched on every request.

2. using static site generation (ssg)

ssg allows you to fetch data at build time. this is useful for pages that do not change frequently.

**example**: fetching data during build time

```javascript

import react from 'react';

const postsstatic = ({ posts }) = {
return (
div
h1static ...

#NextJS #APIIntegration #numpy
API data fetching
client-side data fetching
React hooks API
asynchronous data fetching
fetch data example
Рекомендации по теме
visit shbcf.ru