Skip to content

Commit

Permalink
Doc: ssr fetch, layout
Browse files Browse the repository at this point in the history
  • Loading branch information
oahehc committed Apr 18, 2020
1 parent e6d2108 commit 262db95
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ And to find out the relative syntax in another framework.
- [Basic-Routes](/ssr#basic-routes)
- [Dynamic-Routes](/ssr#dynamic-routes)
- [Link](/ssr#link)
- [Fetch-On-Server](/ssr#fetch-on-server)
- [Layout](/ssr#layout)
- [CLI](/cli)

---
Expand Down
136 changes: 136 additions & 0 deletions SSR.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,142 @@ function Home() {
</template>
```

## Fetch-On-Server

### Next.js

#### < Next.js 9.3

##### class component

```js
import fetch from "isomorphic-unfetch";

export default class Page extends React.Component {
static async getInitialProps(ctx) {
const res = await fetch(`https://.../data`);
const data = await res.json();

return { props: { data } };
}

render() {
// Render data...
}
}
```

##### function component

```js
import fetch from "isomorphic-unfetch";

export default function Page({ data }) {
// Render data...
}

Page.getInitialProps = async (ctx) => {
const res = await fetch(`https://.../data`);
const data = await res.json();

return { props: { data } };
};
```

#### >= Next.js 9.3

```js
import fetch from "isomorphic-unfetch";

function Page({ data }) {
// Render data...
}

export async function getServerSideProps() {
const res = await fetch(`https://.../data`);
const data = await res.json();

return { props: { data } };
}

export default Page;
```

### Nuxt.js

```html
<template>
<div v-if="$fetchState.error">Something went wrong 😭</div>
<div v-if="$fetchState.pending">Loading...</div>
<div v-else>
<h1>{{ post.title }}</h1>
<pre>{{ post.body }}</pre>
<button @click="$fetch">Refresh</button>
</div>
</template>

<script>
import fetch from "node-fetch";
export default {
data() {
return {
post: {},
};
},
async fetch() {
this.post = await this.$http.$get("xxx");
},
fetchOnServer: true,
};
</script>
```

## Layout

### Next.js

`./pages/_app.js`: automatically apply to all pages

```js
export default function MyApp({ Component, pageProps }) {
return (
<React.Fragment>
<MyHeader />
<Component {...pageProps} />
<MyFooter />
</React.Fragment>
);
}
```

### Nuxt.js

`layouts/with-header-footer.vue`: create layout

```html
<template>
<div>
<MyHeader />
<nuxt />
<MyFooter />
</div>
</template>
```

`pages/index.vue`: apply layout

```html
<template>
<!-- Your template -->
</template>
<script>
export default {
layout: "with-header-footer",
};
</script>
```

---

## Reference
Expand Down

0 comments on commit 262db95

Please sign in to comment.