Commit 7fbeca75 authored by Arunoda Susiripala's avatar Arunoda Susiripala

Merge branch 'canary' into multi-zones

parents dc06fee7 e179c98a
#!/usr/bin/env node #!/usr/bin/env node
import { join } from 'path'
import { join, resolve } from 'path'
import { spawn } from 'cross-spawn' import { spawn } from 'cross-spawn'
import { watchFile } from 'fs'
import pkg from '../../package.json' import pkg from '../../package.json'
import getConfig from '../server/config'
if (pkg.peerDependencies) { if (pkg.peerDependencies) {
Object.keys(pkg.peerDependencies).forEach(dependency => { Object.keys(pkg.peerDependencies).forEach(dependency => {
...@@ -88,10 +85,10 @@ const startProcess = () => { ...@@ -88,10 +85,10 @@ const startProcess = () => {
} }
let proc = startProcess() let proc = startProcess()
const { pagesDirectory = resolve(process.cwd(), 'pages') } = getConfig(process.cwd())
if (cmd === 'dev') { if (cmd === 'dev') {
watchFile(`${resolve(pagesDirectory, '..')}/next.config.js`, (cur, prev) => { const {watchFile} = require('fs')
watchFile(`${process.cwd()}/next.config.js`, (cur, prev) => {
if (cur.size > 0 || prev.size > 0) { if (cur.size > 0 || prev.size > 0) {
console.log('\n> Found a change in next.config.js, restarting the server...') console.log('\n> Found a change in next.config.js, restarting the server...')
// Don't listen to 'close' now since otherwise parent gets killed by listener // Don't listen to 'close' now since otherwise parent gets killed by listener
......
...@@ -18,7 +18,7 @@ create-next-app --example active-class-name active-class-name-app ...@@ -18,7 +18,7 @@ create-next-app --example active-class-name active-class-name-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/active-class-name curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/active-class-name
cd active-class-name cd active-class-name
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example basic-css basic-css-app ...@@ -18,7 +18,7 @@ create-next-app --example basic-css basic-css-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/basic-css curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/basic-css
cd basic-css cd basic-css
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-express custom-server-express-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-express custom-server-express-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-express curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-express
cd custom-server-express cd custom-server-express
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-fastify custom-server-fastify-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-fastify custom-server-fastify-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-fastify curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-fastify
cd custom-server-fastify cd custom-server-fastify
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-hapi custom-server-hapi-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-hapi custom-server-hapi-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-hapi curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-hapi
cd custom-server-hapi cd custom-server-hapi
``` ```
......
const pathWrapper = (app, pathName, opts) => ({ raw, query }, hapiReply) => const { parse } = require('url')
app.renderToHTML(raw.req, raw.res, pathName, query, opts)
.then(hapiReply)
const defaultHandlerWrapper = app => { const nextHandlerWrapper = app => {
const handler = app.getRequestHandler() const handler = app.getRequestHandler()
return ({ raw, url }, hapiReply) => return async ({ raw, url }, h) => {
handler(raw.req, raw.res, url) await handler(raw.req, raw.res, url)
.then(() => { return h.close
hapiReply.close(false) }
})
} }
module.exports = { pathWrapper, defaultHandlerWrapper } const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }) => {
const { pathname, query } = parse(url, true)
return app.renderToHTML(req, res, pathname, query)
}
const pathWrapper = (app, pathName, opts) => async ({ raw, query, params }) => {
return app.renderToHTML(raw.req, raw.res, pathName, { ...query, ...params }, opts)
}
module.exports = { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper }
...@@ -7,11 +7,9 @@ ...@@ -7,11 +7,9 @@
"start": "NODE_ENV=production node server.js" "start": "NODE_ENV=production node server.js"
}, },
"dependencies": { "dependencies": {
"hapi": "^16.1.0", "hapi": "^17.1.1",
"next": "latest", "next": "latest",
"react": "^16.0.0", "react": "^16.0.0",
"react-dom": "^16.0.0", "react-dom": "^16.0.0"
"good": "^7.1.0",
"good-console": "^6.2.0"
} }
} }
const next = require('next') const next = require('next')
const Hapi = require('hapi') const Hapi = require('hapi')
const Good = require('good') const { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper } = require('./next-wrapper')
const { pathWrapper, defaultHandlerWrapper } = require('./next-wrapper')
const port = parseInt(process.env.PORT, 10) || 3000 const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production' const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev }) const app = next({ dev })
const server = new Hapi.Server() const server = new Hapi.Server({
port
// add request logging (optional) })
const pluginOptions = [
{
register: Good,
options: {
reporters: {
console: [{
module: 'good-console'
}, 'stdout']
}
}
}
]
app.prepare() app
.then(() => { .prepare()
server.connection({ port }) .then(async () => {
server.register(pluginOptions) server.route({
.then(() => { method: 'GET',
server.route({ path: '/a',
method: 'GET', handler: pathWrapper(app, '/a')
path: '/a', })
handler: pathWrapper(app, '/a')
})
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/b', path: '/b',
handler: pathWrapper(app, '/b') handler: pathWrapper(app, '/b')
}) })
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/{p*}', /* catch all route */ path: '/_next/{p*}', /* next specific routes */
handler: defaultHandlerWrapper(app) handler: nextHandlerWrapper(app)
}) })
server.start().catch(error => { server.route({
console.log('Error starting server') method: 'GET',
console.log(error) path: '/{p*}', /* catch all route */
}).then(() => { handler: defaultHandlerWrapper(app)
console.log(`> Ready on http://localhost:${port}`)
})
}) })
try {
await server.start()
console.log(`> Ready on http://localhost:${port}`)
} catch (error) {
console.log('Error starting server')
console.log(error)
}
}) })
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-koa custom-server-koa-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-koa custom-server-koa-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-koa curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-koa
cd custom-server-koa cd custom-server-koa
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-micro custom-server-micro-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-micro custom-server-micro-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-micro curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-micro
cd custom-server-micro cd custom-server-micro
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server-nodemon custom-server-nodemon-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server-nodemon custom-server-nodemon-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-nodemon curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-nodemon
cd custom-server-nodemon cd custom-server-nodemon
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example custom-server custom-server-app ...@@ -18,7 +18,7 @@ create-next-app --example custom-server custom-server-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
cd custom-server cd custom-server
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example data-fetch data-fetch-app ...@@ -18,7 +18,7 @@ create-next-app --example data-fetch data-fetch-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/data-fetch curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/data-fetch
cd data-fetch cd data-fetch
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example form-handler form-handler-app ...@@ -18,7 +18,7 @@ create-next-app --example form-handler form-handler-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/form-handler curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/form-handler
cd form-handler cd form-handler
``` ```
......
{
"presets": [
"next/babel"
],
"plugins": [
["transform-define", "./env-config.js"]
]
}
# gh-pages Hello World example
## How to use
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/gh-pages
cd gh-pages
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to github
Edit ```env-config.js``` and replace ```'Next-gh-page-example'``` by your project name.
Edit ```next.config.js``` and replace ```'Next-gh-page-example'``` by your project name.
1. Create repository.
2. Link it to your github account.
3. Publish your master branch.
```bash
npm run deploy
```
Test it:
Reaplce 'github-user-name' and 'github-projet-name'
```bash
https://github-user-name.github.io/github-projet-name/
```
Example:
```bash
https://github.com/thierryc/Next-gh-page-example/
https://thierryc.github.io/Next-gh-page-example/
```
## The idea behind the example
This example shows the most basic idea behind Next. We have 2 pages: `pages/index.js` and `pages/about.js`. The former responds to `/` requests and the latter to `/about`. Using `next/link` you can add hyperlinks between them with universal routing capabilities.
const prod = process.env.NODE_ENV === 'production'
module.exports = {
'process.env.BACKEND_URL': prod ? '/Next-gh-page-example' : ''
}
// This file is not going through babel transformation.
// So, we write it in vanilla JS
// (But you could use ES2015 features supported by your Node.js version)
const debug = process.env.NODE_ENV !== 'production'
module.exports = {
exportPathMap: function () {
return {
'/': { page: '/' },
'/about': { page: '/about' }
}
},
assetPrefix: !debug ? '/Next-gh-page-example/' : ''
}
{
"name": "gh-pages",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"export": "next export",
"deploy": "rm -rf node_modules/.cache && next build && next export && touch out/.nojekyll && git add out/ && git commit -m \"Deploy Next.js to gh-pages\" && git subtree push --prefix out origin gh-pages"
},
"dependencies": {
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"license": "ISC",
"devDependencies": {
"babel-plugin-transform-define": "^1.3.0"
}
}
import Link from 'next/link'
export default () => (
<div>
<div>About us</div>
<div>Back to <Link href='/' as={process.env.BACKEND_URL + '/'}><a>Home</a></Link></div>
</div>
)
import Link from 'next/link'
export default () => (
<div>Hello World. <Link href='/about' as={process.env.BACKEND_URL + '/about'}><a>About</a></Link></div>
)
...@@ -18,7 +18,7 @@ create-next-app --example head-elements head-elements-app ...@@ -18,7 +18,7 @@ create-next-app --example head-elements head-elements-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/head-elements curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/head-elements
cd head-elements cd head-elements
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example hello-world hello-world-app ...@@ -18,7 +18,7 @@ create-next-app --example hello-world hello-world-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/hello-world curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/hello-world
cd hello-world cd hello-world
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example layout-component layout-component-app ...@@ -18,7 +18,7 @@ create-next-app --example layout-component layout-component-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/layout-component curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/layout-component
cd layout-component cd layout-component
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example nested-components nested-components-app ...@@ -18,7 +18,7 @@ create-next-app --example nested-components nested-components-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/nested-components curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/nested-components
cd nested-components cd nested-components
``` ```
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/only-client-render-external-dependencies curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/only-client-render-external-dependencies
cd only-client-render-external-dependencies cd only-client-render-external-dependencies
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example page-transitions page-transitions-app ...@@ -18,7 +18,7 @@ create-next-app --example page-transitions page-transitions-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/page-transitions curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/page-transitions
cd page-transitions cd page-transitions
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example parameterized-routing parameterized-routing-app ...@@ -18,7 +18,7 @@ create-next-app --example parameterized-routing parameterized-routing-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/parameterized-routing curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/parameterized-routing
cd parameterized-routing cd parameterized-routing
``` ```
......
...@@ -17,7 +17,7 @@ create-next-app --example progressive-render progressive-render-app ...@@ -17,7 +17,7 @@ create-next-app --example progressive-render progressive-render-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/progressive-render curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/progressive-render
cd progressive-render cd progressive-render
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example root-static-files root-static-files-app ...@@ -18,7 +18,7 @@ create-next-app --example root-static-files root-static-files-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
cd custom-server cd custom-server
``` ```
......
...@@ -17,7 +17,7 @@ create-next-app --example shared-modules shared-modules-app ...@@ -17,7 +17,7 @@ create-next-app --example shared-modules shared-modules-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/shared-modules curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/shared-modules
cd shared-modules cd shared-modules
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example ssr-caching ssr-caching-app ...@@ -18,7 +18,7 @@ create-next-app --example ssr-caching ssr-caching-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/ssr-caching curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/ssr-caching
cd ssr-caching cd ssr-caching
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example svg-components svg-components-app ...@@ -18,7 +18,7 @@ create-next-app --example svg-components svg-components-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/svg-components curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/svg-components
cd svg-components cd svg-components
``` ```
......
...@@ -7,7 +7,9 @@ ...@@ -7,7 +7,9 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"next": "latest" "next": "latest",
"react": "latest,
"react-dom": "latest"
}, },
"devDependencies": { "devDependencies": {
"babel-plugin-inline-react-svg": "^0.2.0" "babel-plugin-inline-react-svg": "^0.2.0"
......
...@@ -18,7 +18,7 @@ create-next-app --example using-inferno using-inferno-app ...@@ -18,7 +18,7 @@ create-next-app --example using-inferno using-inferno-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-inferno curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-inferno
cd using-inferno cd using-inferno
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example using-preact using-preact-app ...@@ -18,7 +18,7 @@ create-next-app --example using-preact using-preact-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-preact curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-preact
cd using-preact cd using-preact
``` ```
......
...@@ -17,7 +17,7 @@ create-next-app --example using-router using-router-app ...@@ -17,7 +17,7 @@ create-next-app --example using-router using-router-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-router curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-router
cd using-router cd using-router
``` ```
......
...@@ -17,7 +17,7 @@ create-next-app --example using-with-router using-with-router-app ...@@ -17,7 +17,7 @@ create-next-app --example using-with-router using-with-router-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-with-router curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-with-router
cd using-with-router cd using-with-router
``` ```
......
...@@ -16,7 +16,7 @@ create-next-app --example with-absolute-imports with-absolute-imports-app ...@@ -16,7 +16,7 @@ create-next-app --example with-absolute-imports with-absolute-imports-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-absolute-import curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-absolute-import
cd with-absolute-import cd with-absolute-import
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-algolia-react-instantsearch with-algolia-react-in ...@@ -18,7 +18,7 @@ create-next-app --example with-algolia-react-instantsearch with-algolia-react-in
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-algolia-react-instantsearch curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-algolia-react-instantsearch
cd with-algolia-react-instantsearch cd with-algolia-react-instantsearch
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-amp with-amp-app ...@@ -18,7 +18,7 @@ create-next-app --example with-amp with-amp-app
Download the example [or clone the repo](https://github.com/zeit/next.js.git): Download the example [or clone the repo](https://github.com/zeit/next.js.git):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-amp curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-amp
cd with-amp cd with-amp
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-ant-design with-ant-design-app ...@@ -18,7 +18,7 @@ create-next-app --example with-ant-design with-ant-design-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-ant-design curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-ant-design
cd with-ant-design cd with-ant-design
``` ```
......
...@@ -4,7 +4,7 @@ export default ({ children }) => ...@@ -4,7 +4,7 @@ export default ({ children }) =>
<Head> <Head>
<meta name='viewport' content='width=device-width, initial-scale=1' /> <meta name='viewport' content='width=device-width, initial-scale=1' />
<meta charSet='utf-8' /> <meta charSet='utf-8' />
<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/antd/2.9.3/antd.min.css' /> <link rel='stylesheet' href='https://unpkg.com/antd@3/dist/antd.min.css' />
</Head> </Head>
<style jsx global>{` <style jsx global>{`
body { body {
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"antd": "^2.10.2", "antd": "^3.0.2",
"babel-plugin-import": "^1.1.1", "babel-plugin-import": "^1.1.1",
"next": "latest", "next": "latest",
"react": "^16.0.0", "react": "^16.0.0",
......
import Layout from '../index.js' import Layout from '../index.js'
import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button, LocaleProvider } from 'antd' import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd'
import enUS from 'antd/lib/locale-provider/en_US'
const FormItem = Form.Item const FormItem = Form.Item
const Option = Select.Option const Option = Select.Option
export default () => ( export default () => (
<Layout> <Layout>
<LocaleProvider locale={enUS}> <div style={{ marginTop: 100 }}>
<div style={{ marginTop: 100 }}> <Form layout='horizontal'>
<Form layout='horizontal'> <FormItem
<FormItem label='Input Number'
label='Input Number' labelCol={{ span: 8 }}
labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}
wrapperCol={{ span: 8 }} >
> <InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' /> <a href='#'>Link</a>
<a href='#'>Link</a> </FormItem>
</FormItem>
<FormItem <FormItem
label='Switch' label='Switch'
labelCol={{ span: 8 }} labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }} wrapperCol={{ span: 8 }}
> >
<Switch defaultChecked name='switch' /> <Switch defaultChecked name='switch' />
</FormItem> </FormItem>
<FormItem <FormItem
label='Slider' label='Slider'
labelCol={{ span: 8 }} labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }} wrapperCol={{ span: 8 }}
> >
<Slider defaultValue={70} /> <Slider defaultValue={70} />
</FormItem> </FormItem>
<FormItem <FormItem
label='Select' label='Select'
labelCol={{ span: 8 }} labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }} wrapperCol={{ span: 8 }}
> >
<Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'> <Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<Option value='jack'>jack</Option> <Option value='jack'>jack</Option>
<Option value='lucy'>lucy</Option> <Option value='lucy'>lucy</Option>
<Option value='disabled' disabled>disabled</Option> <Option value='disabled' disabled>disabled</Option>
<Option value='yiminghe'>yiminghe</Option> <Option value='yiminghe'>yiminghe</Option>
</Select> </Select>
</FormItem> </FormItem>
<FormItem <FormItem
label='DatePicker' label='DatePicker'
labelCol={{ span: 8 }} labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }} wrapperCol={{ span: 8 }}
> >
<DatePicker name='startDate' /> <DatePicker name='startDate' />
</FormItem> </FormItem>
<FormItem <FormItem
style={{ marginTop: 48 }} style={{ marginTop: 48 }}
wrapperCol={{ span: 8, offset: 8 }} wrapperCol={{ span: 8, offset: 8 }}
> >
<Button size='large' type='primary' htmlType='submit'> <Button size='large' type='primary' htmlType='submit'>
OK OK
</Button> </Button>
<Button size='large' style={{ marginLeft: 8 }}> <Button size='large' style={{ marginLeft: 8 }}>
Cancel Cancel
</Button> </Button>
</FormItem> </FormItem>
</Form> </Form>
</div> </div>
</LocaleProvider>
</Layout> </Layout>
) )
...@@ -17,7 +17,7 @@ create-next-app --example with-antd-mobile with-antd-mobile-app ...@@ -17,7 +17,7 @@ create-next-app --example with-antd-mobile with-antd-mobile-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-antd-mobile curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-antd-mobile
cd with-antd-mobile cd with-antd-mobile
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-aphrodite with-aphrodite-app ...@@ -18,7 +18,7 @@ create-next-app --example with-aphrodite with-aphrodite-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-aphrodite curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-aphrodite
cd with-aphrodite cd with-aphrodite
``` ```
......
...@@ -17,7 +17,7 @@ create-next-app --example with-apollo-and-redux with-apollo-and-redux-app ...@@ -17,7 +17,7 @@ create-next-app --example with-apollo-and-redux with-apollo-and-redux-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo-and-redux curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo-and-redux
cd with-apollo-and-redux cd with-apollo-and-redux
``` ```
...@@ -35,9 +35,9 @@ now ...@@ -35,9 +35,9 @@ now
``` ```
## The idea behind the example ## The idea behind the example
By default, Apollo Client creates its own internal Redux store to manage queries and their results. If you are already using Redux for the rest of your app, [you can have the client integrate with your existing store instead](http://dev.apollodata.com/react/redux.html), which is what this example does. This example is identical to the [`with-apollo`](https://github.com/zeit/next.js/tree/master/examples/with-apollo) with the exception of this Redux store integration. In 2.0.0, Apollo Client severs out-of-the-box support for redux in favor of Apollo's client side state management. This example aims to be an amalgamation of the [`with-apollo`](https://github.com/zeit/next.js/tree/master/examples/with-apollo) and [`with-redux`](https://github.com/zeit/next.js/tree/master/examples/with-redux) examples.
Note that you can acesss the redux store like you normally would using `react-redux`'s `connect` as per [here](http://dev.apollodata.com/react/redux.html#using-connect). Here's a quick example: Note that you can access the redux store like you normally would using `react-redux`'s `connect`. Here's a quick example:
```js ```js
const mapStateToProps = state => ({ const mapStateToProps = state => ({
...@@ -47,5 +47,4 @@ const mapStateToProps = state => ({ ...@@ -47,5 +47,4 @@ const mapStateToProps = state => ({
export default withData(connect(mapStateToProps, null)(Index)); export default withData(connect(mapStateToProps, null)(Index));
``` ```
`connect` must go inside `withData` otherwise `connect` will not be able to find the store. `connect` must go inside `withData` otherwise `connect` will not be able to find the store.
import Link from 'next/link' import Link from 'next/link'
import { withRouter } from 'next/router'
export default ({ pathname }) => ( const Header = ({ router: { pathname } }) => (
<header> <header>
<Link prefetch href='/'> <Link prefetch href='/'>
<a className={pathname === '/' && 'is-active'}>Home</a> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link> </Link>
<Link prefetch href='/about'> <Link prefetch href='/about'>
<a className={pathname === '/about' && 'is-active'}>About</a> <a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link> </Link>
<Link prefetch href='/blog'> <Link prefetch href='/blog'>
<a className={pathname === '/blog' && 'is-active'}>Blog</a> <a className={pathname === '/blog' ? 'is-active' : ''}>Blog</a>
</Link> </Link>
<style jsx>{` <style jsx>{`
header { header {
margin-bottom: 25px; margin-bottom: 25px;
...@@ -29,3 +27,5 @@ export default ({ pathname }) => ( ...@@ -29,3 +27,5 @@ export default ({ pathname }) => (
`}</style> `}</style>
</header> </header>
) )
export default withRouter(Header)
import React from 'react' import React from 'react'
import { gql, graphql } from 'react-apollo' import { withRouter } from 'next/router'
import PostUpvoter from './PostUpvoter' import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
function Post ({ id, data: { loading, error, Post } }) { import ErrorMessage from './ErrorMessage'
return ( import PostVoteUp from './PostVoteUp'
<section> import PostVoteDown from './PostVoteDown'
<div key={Post.id}> import PostVoteCount from './PostVoteCount'
<h1>{Post.title}</h1>
<p>ID: {Post.id}<br />URL: {Post.url}</p> function Post ({ id, data: { error, Post } }) {
<PostUpvoter id={Post.id} votes={Post.votes} /> if (error) return <ErrorMessage message='Error loading blog post.' />
</div> if (Post) {
</section> return (
) <section>
<div key={Post.id}>
<h1>{Post.title}</h1>
<p>ID: {Post.id}<br />URL: {Post.url}</p>
<span>
<PostVoteUp id={Post.id} votes={Post.votes} />
<PostVoteCount votes={Post.votes} />
<PostVoteDown id={Post.id} votes={Post.votes} />
</span>
</div>
<style jsx>{`
span {
display: flex;
font-size: 14px;
margin-right: 5px;
}
`}</style>
</section>
)
}
return <div>Loading</div>
} }
const post = gql` const post = gql`
query post($id: ID!) { query post($id: ID!) {
Post(id: $id) { Post(id: $id) {
id id
title title
votes votes
url url
createdAt createdAt
}
} }
}
` `
// The `graphql` wrapper executes a GraphQL query and makes the results // The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList) // available on the `data` prop of the wrapped component (Post)
// Tip: ownProps is parent component's props const ComponentWithMutation = graphql(post, {
export default graphql(post, { options: ({ router: { query } }) => ({
options: (ownProps) => { variables: {
return { id: query.id
variables: {
id: ownProps.id
}
} }
} }),
props: ({ data }) => ({
data
})
})(Post) })(Post)
export default withRouter(ComponentWithMutation)
import { gql, graphql } from 'react-apollo' import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { Router } from '../routes'
import ErrorMessage from './ErrorMessage' import ErrorMessage from './ErrorMessage'
import PostUpvoter from './PostUpvoter' import PostVoteUp from './PostVoteUp'
import Link from 'next/link' import PostVoteDown from './PostVoteDown'
import PostVoteCount from './PostVoteCount'
const POSTS_PER_PAGE = 10 const POSTS_PER_PAGE = 10
function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMorePosts }) { function handleClick (event, id) {
event.preventDefault()
// With route name and params
// Router.pushRoute('blog/entry', { id: id })
// With route URL
Router.pushRoute(`/blog/${id}`)
}
function PostList ({
data: { loading, error, allPosts, _allPostsMeta },
loadMorePosts
}) {
if (error) return <ErrorMessage message='Error loading posts.' /> if (error) return <ErrorMessage message='Error loading posts.' />
if (allPosts && allPosts.length) { if (allPosts && allPosts.length) {
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
<section> <section>
<ul> <ul>
{allPosts.map((post, index) => {allPosts.map((post, index) => (
<li key={post.id}> <li key={post.id}>
<div> <div>
<span>{index + 1}. </span> <span>{index + 1}. </span>
<Link href={{ pathname: '/blog/' + post.id }}><a>{post.title}</a></Link> <a
<PostUpvoter id={post.id} votes={post.votes} /> href={`/blog/${post.id}`}
onClick={(event) => handleClick(event, post.id)}
>
{post.title}
</a>
<PostVoteUp id={post.id} votes={post.votes} />
<PostVoteCount votes={post.votes} />
<PostVoteDown id={post.id} votes={post.votes} />
</div> </div>
</li> </li>
)} ))}
</ul> </ul>
{areMorePosts ? <button onClick={() => loadMorePosts()}> {loading ? 'Loading...' : 'Show More'} </button> : ''} {areMorePosts ? (
<button onClick={() => loadMorePosts()}>
{' '}
{loading ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{` <style jsx>{`
section { section {
padding-bottom: 20px; padding-bottom: 20px;
...@@ -55,7 +83,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -55,7 +83,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
border-style: solid; border-style: solid;
border-width: 6px 4px 0 4px; border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent; border-color: #ffffff transparent transparent transparent;
content: ""; content: '';
height: 0; height: 0;
margin-right: 5px; margin-right: 5px;
width: 0; width: 0;
...@@ -67,7 +95,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -67,7 +95,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
return <div>Loading</div> return <div>Loading</div>
} }
const allPosts = gql` export const allPosts = gql`
query allPosts($first: Int!, $skip: Int!) { query allPosts($first: Int!, $skip: Int!) {
allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) { allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) {
id id
...@@ -75,21 +103,23 @@ const allPosts = gql` ...@@ -75,21 +103,23 @@ const allPosts = gql`
votes votes
url url
createdAt createdAt
}, }
_allPostsMeta { _allPostsMeta {
count count
} }
} }
` `
export const allPostsQueryVars = {
skip: 0,
first: POSTS_PER_PAGE
}
// The `graphql` wrapper executes a GraphQL query and makes the results // The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList) // available on the `data` prop of the wrapped component (PostList)
export default graphql(allPosts, { export default graphql(allPosts, {
options: { options: {
variables: { variables: allPostsQueryVars
skip: 0,
first: POSTS_PER_PAGE
}
}, },
props: ({ data }) => ({ props: ({ data }) => ({
data, data,
......
import React from 'react'
import { gql, graphql } from 'react-apollo'
function PostUpvoter ({ upvote, votes, id }) {
return (
<button onClick={() => upvote(id, votes + 1)}>
{votes}
<style jsx>{`
button {
background-color: transparent;
border: 1px solid #e4e4e4;
color: #000;
}
button:active {
background-color: transparent;
}
button:before {
align-self: center;
border-color: transparent transparent #000000 transparent;
border-style: solid;
border-width: 0 4px 6px 4px;
content: "";
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</button>
)
}
const upvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
export default graphql(upvotePost, {
props: ({ ownProps, mutate }) => ({
upvote: (id, votes) => mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id: ownProps.id,
votes: ownProps.votes + 1
}
}
})
})
})(PostUpvoter)
export default ({onClickHandler, className}) => (
<button className={className} onClick={() => onClickHandler()}>
<style jsx>{`
button {
background-color: transparent;
border: 1px solid #e4e4e4;
color: #000;
}
button:active {
background-color: transparent;
}
button:before {
align-self: center;
border-color: transparent transparent #000000 transparent;
border-style: solid;
border-width: 0 4px 6px 4px;
content: '';
height: 0;
margin-right: 0px;
width: 0;
}
.downvote {
transform: rotate(180deg);
}
.upvote {
transform: rotate(0deg);
}
`}</style>
</button>
)
export default ({votes}) => (
<span>
{votes}
<style jsx>{`
span {
padding: 0.5em 0.5em;
font-size: 14px;
color: inherit;
}
`}</style>
</span>
)
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import PostVoteButton from './PostVoteButton'
function PostVoteDown ({ downvote, votes, id }) {
return (
<PostVoteButton
className='downvote'
onClickHandler={() => downvote(id, votes - 1)}
/>
)
}
const downvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
export default graphql(downvotePost, {
props: ({ ownProps, mutate }) => ({
downvote: (id, votes) =>
mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id: ownProps.id,
votes: ownProps.votes - 1
}
}
})
})
})(PostVoteDown)
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import PostVoteButton from './PostVoteButton'
function PostVoteUp ({ upvote, votes, id }) {
return (
<PostVoteButton
className='upvote'
onClickHandler={() => upvote(id, votes + 1)}
/>
)
}
const upvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
export default graphql(upvotePost, {
props: ({ ownProps, mutate }) => ({
upvote: (id, votes) =>
mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id: ownProps.id,
votes: ownProps.votes + 1
}
}
})
})
})(PostVoteUp)
import { gql, graphql } from 'react-apollo' import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { allPosts, allPostsQueryVars } from './PostList'
function Submit ({ createPost }) { function Submit ({ createPost }) {
function handleSubmit (e) { function handleSubmit (event) {
e.preventDefault() event.preventDefault()
let title = e.target.elements.title.value const form = event.target
let url = e.target.elements.url.value
if (title === '' || url === '') { const formData = new window.FormData(form)
window.alert('Both fields are required.') createPost(formData.get('title'), formData.get('url'))
return false
}
// prepend http if missing from url
if (!url.match(/^[a-zA-Z]+:\/\//)) {
url = `http://${url}`
}
createPost(title, url) form.reset()
// reset form
e.target.elements.title.value = ''
e.target.elements.url.value = ''
} }
return ( return (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<h1>Submit</h1> <h1>Submit</h1>
<input placeholder='title' name='title' /> <input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' /> <input placeholder='url' name='url' type='url' required />
<button type='submit'>Submit</button> <button type='submit'>Submit</button>
<style jsx>{` <style jsx>{`
form { form {
...@@ -62,17 +52,23 @@ const createPost = gql` ...@@ -62,17 +52,23 @@ const createPost = gql`
export default graphql(createPost, { export default graphql(createPost, {
props: ({ mutate }) => ({ props: ({ mutate }) => ({
createPost: (title, url) => mutate({ createPost: (title, url) =>
variables: { title, url }, mutate({
updateQueries: { variables: { title, url },
allPosts: (previousResult, { mutationResult }) => { update: (proxy, { data: { createPost } }) => {
const newPost = mutationResult.data.createPost const data = proxy.readQuery({
return Object.assign({}, previousResult, { query: allPosts,
// Append the new post variables: allPostsQueryVars
allPosts: [newPost, ...previousResult.allPosts] })
proxy.writeQuery({
query: allPosts,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
}) })
} }
} })
})
}) })
})(Submit) })(Submit)
import { ApolloClient, createNetworkInterface } from 'react-apollo' import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import fetch from 'isomorphic-unfetch' import fetch from 'isomorphic-unfetch'
let apolloClient = null let apolloClient = null
...@@ -8,28 +10,28 @@ if (!process.browser) { ...@@ -8,28 +10,28 @@ if (!process.browser) {
global.fetch = fetch global.fetch = fetch
} }
function create () { function create(initialState) {
return new ApolloClient({ return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
networkInterface: createNetworkInterface({ link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute) uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
opts: { // Additional fetch() options like `credentials` or `headers` credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers`
credentials: 'same-origin' }),
} cache: new InMemoryCache().restore(initialState || {})
})
}) })
} }
export default function initApollo () { export default function initApollo(initialState) {
// Make sure to create a new client for every server-side request so that data // Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad) // isn't shared between connections (which would be bad)
if (!process.browser) { if (!process.browser) {
return create() return create(initialState)
} }
// Reuse client on the client-side // Reuse client on the client-side
if (!apolloClient) { if (!apolloClient) {
apolloClient = create() apolloClient = create(initialState)
} }
return apolloClient return apolloClient
......
...@@ -12,27 +12,26 @@ if (process.browser && window.__REDUX_DEVTOOLS_EXTENSION__) { ...@@ -12,27 +12,26 @@ if (process.browser && window.__REDUX_DEVTOOLS_EXTENSION__) {
function create (apollo, initialState = {}) { function create (apollo, initialState = {}) {
return createStore( return createStore(
combineReducers({ // Setup reducers combineReducers({ // Setup reducers
...reducers, ...reducers
apollo: apollo.reducer()
}), }),
initialState, // Hydrate the store with server-side data initialState, // Hydrate the store with server-side data
compose( compose(
applyMiddleware(apollo.middleware()), // Add additional middleware here // Add additional middleware here
devtools devtools
) )
) )
} }
export default function initRedux (apollo, initialState) { export default function initRedux (initialState) {
// Make sure to create a new store for every server-side request so that data // Make sure to create a new store for every server-side request so that data
// isn't shared between connections (which would be bad) // isn't shared between connections (which would be bad)
if (!process.browser) { if (!process.browser) {
return create(apollo, initialState) return create(initialState)
} }
// Reuse store on the client-side // Reuse store on the client-side
if (!reduxStore) { if (!reduxStore) {
reduxStore = create(apollo, initialState) reduxStore = create(initialState)
} }
return reduxStore return reduxStore
......
export default { export default {
example: (state = {}, { type, payload }) => { redux: (state = {}, { type, payload }) => {
switch (type) { switch (type) {
case 'EXAMPLE_ACTION': case 'EXAMPLE_ACTION':
return { return {
......
...@@ -6,19 +6,28 @@ import initApollo from './initApollo' ...@@ -6,19 +6,28 @@ import initApollo from './initApollo'
import initRedux from './initRedux' import initRedux from './initRedux'
// Gets the display name of a JSX component for dev tools // Gets the display name of a JSX component for dev tools
function getComponentDisplayName (Component) { function getComponentDisplayName(Component) {
return Component.displayName || Component.name || 'Unknown' return Component.displayName || Component.name || 'Unknown'
} }
export default ComposedComponent => { export default ComposedComponent => {
return class WithData extends React.Component { return class WithData extends React.Component {
static displayName = `WithData(${getComponentDisplayName(ComposedComponent)})` static displayName = `WithData(${getComponentDisplayName(
ComposedComponent
)})`
static propTypes = { static propTypes = {
serverState: PropTypes.object.isRequired stateApollo: PropTypes.object.isRequired
} }
static async getInitialProps (ctx) { static async getInitialProps(ctx) {
let serverState = {} // Initial stateApollo with apollo (empty)
let stateApollo = {
apollo: {
data: {}
}
}
// Initial stateRedux with apollo (empty)
let stateRedux = {}
// Evaluate the composed component's getInitialProps() // Evaluate the composed component's getInitialProps()
let composedInitialProps = {} let composedInitialProps = {}
...@@ -30,18 +39,21 @@ export default ComposedComponent => { ...@@ -30,18 +39,21 @@ export default ComposedComponent => {
// and extract the resulting data // and extract the resulting data
if (!process.browser) { if (!process.browser) {
const apollo = initApollo() const apollo = initApollo()
const redux = initRedux(apollo) const redux = initRedux()
// Provide the `url` prop data in case a GraphQL query uses it
const url = {query: ctx.query, pathname: ctx.pathname}
try { try {
// Run all GraphQL queries // Run all GraphQL queries
await getDataFromTree( await getDataFromTree(
// No need to use the Redux Provider <ApolloProvider client={apollo}>
// because Apollo sets up the store for us <ComposedComponent {...composedInitialProps} />
<ApolloProvider client={apollo} store={redux}> </ApolloProvider>,
<ComposedComponent url={url} {...composedInitialProps} /> {
</ApolloProvider> router: {
asPath: ctx.asPath,
pathname: ctx.pathname,
query: ctx.query
}
}
) )
} catch (error) { } catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR. // Prevent Apollo Client GraphQL errors from crashing SSR.
...@@ -52,35 +64,33 @@ export default ComposedComponent => { ...@@ -52,35 +64,33 @@ export default ComposedComponent => {
// head side effect therefore need to be cleared manually // head side effect therefore need to be cleared manually
Head.rewind() Head.rewind()
// Extract query data from the store // Extract query data from the Redux store
const state = redux.getState() stateRedux = redux.getState()
// No need to include other initial Redux state because when it // Extract query data from the Apollo store
// initialises on the client-side it'll create it again anyway stateApollo = {
serverState = { apollo: {
apollo: { // Only include the Apollo data state data: apollo.cache.extract()
data: state.apollo.data
} }
} }
} }
return { return {
serverState, stateApollo,
stateRedux,
...composedInitialProps ...composedInitialProps
} }
} }
constructor (props) { constructor(props) {
super(props) super(props)
this.apollo = initApollo() this.apollo = initApollo(props.stateApollo.apollo.data)
this.redux = initRedux(this.apollo, this.props.serverState) this.redux = initRedux(props.stateRedux)
} }
render () { render() {
return ( return (
// No need to use the Redux Provider <ApolloProvider client={this.apollo}>
// because Apollo sets up the store for us
<ApolloProvider client={this.apollo} store={this.redux}>
<ComposedComponent {...this.props} /> <ComposedComponent {...this.props} />
</ApolloProvider> </ApolloProvider>
) )
......
...@@ -7,15 +7,19 @@ ...@@ -7,15 +7,19 @@
"start": "NODE_ENV=production node server.js" "start": "NODE_ENV=production node server.js"
}, },
"dependencies": { "dependencies": {
"graphql": "^0.9.3", "apollo-cache-inmemory": "1.1.4",
"apollo-client-preset": "^1.0.4",
"graphql": "^0.11.7",
"graphql-anywhere": "^4.0.2",
"graphql-tag": "^2.5.0",
"isomorphic-unfetch": "^2.0.0", "isomorphic-unfetch": "^2.0.0",
"next": "latest", "next": "latest",
"next-routes": "^1.1.0", "next-routes": "^1.2.0",
"prop-types": "^15.5.8", "prop-types": "^15.6.0",
"react": "^16.0.0", "react": "^16.0.0",
"react-apollo": "^1.1.3", "react-apollo": "^2.0.0",
"react-dom": "^16.0.0", "react-dom": "^16.0.0",
"redux": "^3.6.0" "redux": "^3.7.0"
}, },
"author": "", "author": "",
"license": "ISC" "license": "ISC"
......
import App from '../components/App' import App from '../components/App'
import Header from '../components/Header' import Header from '../components/Header'
export default (props) => ( export default () => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<article> <article>
<h1>The Idea Behind This Example</h1> <h1>The Idea Behind This Example</h1>
<p> <p>
......
import withData from '../../lib/withData'
import App from '../../components/App' import App from '../../components/App'
import Header from '../../components/Header' import Header from '../../components/Header'
import Post from '../../components/Post' import Post from '../../components/Post'
import withData from '../../lib/withData'
export default withData((props) => ( export default withData((props) => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<Post id={props.url.query.id} /> <Post />
</App> </App>
)) ))
import withData from '../../lib/withData'
import App from '../../components/App' import App from '../../components/App'
import Header from '../../components/Header' import Header from '../../components/Header'
import Submit from '../../components/Submit' import Submit from '../../components/Submit'
import PostList from '../../components/PostList' import PostList from '../../components/PostList'
import withData from '../../lib/withData'
export default withData((props) => ( export default withData(() => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<Submit /> <Submit />
<PostList /> <PostList />
</App> </App>
......
import withData from '../lib/withData'
import App from '../components/App' import App from '../components/App'
import Header from '../components/Header' import Header from '../components/Header'
import withData from '../lib/withData'
export default withData((props) => ( export default withData(() => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<h1>Welcome Home.</h1> <h1>Welcome Home.</h1>
</App> </App>
)) ))
/**
* Parameterized Routing with next-route
*
* Benefits: Less code, and easily handles complex url structures
**/
const routes = (module.exports = require('next-routes')())
routes.add('blog/entry', '/blog/:id')
...@@ -19,15 +19,7 @@ const next = require('next') ...@@ -19,15 +19,7 @@ const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000 const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production' const dev = process.env.NODE_ENV !== 'production'
const app = next({dev}) const app = next({dev})
const routes = require('./routes')
/**
* Parameterized Routing with next-route
*
* Benefits: Less code, and easily handles complex url structures
*/
const routes = require('next-routes')()
routes.add('blog/entry', '/blog/:id')
const handler = routes.getRequestHandler(app) const handler = routes.getRequestHandler(app)
app.prepare().then(() => { app.prepare().then(() => {
......
...@@ -21,7 +21,7 @@ create-next-app --example with-apollo-auth with-apollo-auth-app ...@@ -21,7 +21,7 @@ create-next-app --example with-apollo-auth with-apollo-auth-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo-auth curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo-auth
cd with-apollo-auth cd with-apollo-auth
``` ```
......
...@@ -21,7 +21,7 @@ create-next-app --example with-apollo with-apollo-app ...@@ -21,7 +21,7 @@ create-next-app --example with-apollo with-apollo-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo
cd with-apollo cd with-apollo
``` ```
......
...@@ -3,14 +3,16 @@ export default ({ children }) => ( ...@@ -3,14 +3,16 @@ export default ({ children }) => (
{children} {children}
<style jsx global>{` <style jsx global>{`
* { * {
font-family: Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif; font-family: Menlo, Monaco, 'Lucida Console', 'Liberation Mono',
'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New',
monospace, serif;
} }
body { body {
margin: 0; margin: 0;
padding: 25px 50px; padding: 25px 50px;
} }
a { a {
color: #22BAD9; color: #22bad9;
} }
p { p {
font-size: 14px; font-size: 14px;
...@@ -22,15 +24,15 @@ export default ({ children }) => ( ...@@ -22,15 +24,15 @@ export default ({ children }) => (
} }
button { button {
align-items: center; align-items: center;
background-color: #22BAD9; background-color: #22bad9;
border: 0; border: 0;
color: white; color: white;
display: flex; display: flex;
padding: 5px 7px; padding: 5px 7px;
} }
button:active { button:active {
background-color: #1B9DB7; background-color: #1b9db7;
transition: background-color .3s transition: background-color 0.3s;
} }
button:focus { button:focus {
outline: none; outline: none;
......
export default ({message}) => ( export default ({ message }) => (
<aside> <aside>
{message} {message}
<style jsx>{` <style jsx>{`
......
import Link from 'next/link' import Link from 'next/link'
import { withRouter } from 'next/router'
export default ({ pathname }) => ( const Header = ({ router: { pathname } }) => (
<header> <header>
<Link prefetch href='/'> <Link prefetch href='/'>
<a className={pathname === '/' && 'is-active'}>Home</a> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link> </Link>
<Link prefetch href='/about'> <Link prefetch href='/about'>
<a className={pathname === '/about' && 'is-active'}>About</a> <a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link> </Link>
<style jsx>{` <style jsx>{`
header { header {
margin-bottom: 25px; margin-bottom: 25px;
...@@ -25,3 +24,5 @@ export default ({ pathname }) => ( ...@@ -25,3 +24,5 @@ export default ({ pathname }) => (
`}</style> `}</style>
</header> </header>
) )
export default withRouter(Header)
...@@ -5,14 +5,17 @@ import PostUpvoter from './PostUpvoter' ...@@ -5,14 +5,17 @@ import PostUpvoter from './PostUpvoter'
const POSTS_PER_PAGE = 10 const POSTS_PER_PAGE = 10
function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMorePosts }) { function PostList ({
data: { loading, error, allPosts, _allPostsMeta },
loadMorePosts
}) {
if (error) return <ErrorMessage message='Error loading posts.' /> if (error) return <ErrorMessage message='Error loading posts.' />
if (allPosts && allPosts.length) { if (allPosts && allPosts.length) {
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
<section> <section>
<ul> <ul>
{allPosts.map((post, index) => {allPosts.map((post, index) => (
<li key={post.id}> <li key={post.id}>
<div> <div>
<span>{index + 1}. </span> <span>{index + 1}. </span>
...@@ -20,9 +23,16 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -20,9 +23,16 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
<PostUpvoter id={post.id} votes={post.votes} /> <PostUpvoter id={post.id} votes={post.votes} />
</div> </div>
</li> </li>
)} ))}
</ul> </ul>
{areMorePosts ? <button onClick={() => loadMorePosts()}> {loading ? 'Loading...' : 'Show More'} </button> : ''} {areMorePosts ? (
<button onClick={() => loadMorePosts()}>
{' '}
{loading ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{` <style jsx>{`
section { section {
padding-bottom: 20px; padding-bottom: 20px;
...@@ -55,7 +65,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -55,7 +65,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
border-style: solid; border-style: solid;
border-width: 6px 4px 0 4px; border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent; border-color: #ffffff transparent transparent transparent;
content: ""; content: '';
height: 0; height: 0;
margin-right: 5px; margin-right: 5px;
width: 0; width: 0;
...@@ -75,7 +85,7 @@ export const allPosts = gql` ...@@ -75,7 +85,7 @@ export const allPosts = gql`
votes votes
url url
createdAt createdAt
}, }
_allPostsMeta { _allPostsMeta {
count count
} }
......
...@@ -20,7 +20,7 @@ function PostUpvoter ({ upvote, votes, id }) { ...@@ -20,7 +20,7 @@ function PostUpvoter ({ upvote, votes, id }) {
border-color: transparent transparent #000000 transparent; border-color: transparent transparent #000000 transparent;
border-style: solid; border-style: solid;
border-width: 0 4px 6px 4px; border-width: 0 4px 6px 4px;
content: ""; content: '';
height: 0; height: 0;
margin-right: 5px; margin-right: 5px;
width: 0; width: 0;
...@@ -42,16 +42,17 @@ const upvotePost = gql` ...@@ -42,16 +42,17 @@ const upvotePost = gql`
export default graphql(upvotePost, { export default graphql(upvotePost, {
props: ({ ownProps, mutate }) => ({ props: ({ ownProps, mutate }) => ({
upvote: (id, votes) => mutate({ upvote: (id, votes) =>
variables: { id, votes }, mutate({
optimisticResponse: { variables: { id, votes },
__typename: 'Mutation', optimisticResponse: {
updatePost: { __typename: 'Mutation',
__typename: 'Post', updatePost: {
id: ownProps.id, __typename: 'Post',
votes: ownProps.votes + 1 id: ownProps.id,
votes: ownProps.votes + 1
}
} }
} })
})
}) })
})(PostUpvoter) })(PostUpvoter)
import { graphql } from 'react-apollo' import { graphql } from 'react-apollo'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import {allPosts, allPostsQueryVars} from './PostList' import { allPosts, allPostsQueryVars } from './PostList'
function Submit ({ createPost }) { function Submit ({ createPost }) {
function handleSubmit (e) { function handleSubmit (event) {
e.preventDefault() event.preventDefault()
let title = e.target.elements.title.value const form = event.target
let url = e.target.elements.url.value
if (title === '' || url === '') { const formData = new window.FormData(form)
window.alert('Both fields are required.') createPost(formData.get('title'), formData.get('url'))
return false
}
// prepend http if missing from url
if (!url.match(/^[a-zA-Z]+:\/\//)) {
url = `http://${url}`
}
createPost(title, url) form.reset()
// reset form
e.target.elements.title.value = ''
e.target.elements.url.value = ''
} }
return ( return (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<h1>Submit</h1> <h1>Submit</h1>
<input placeholder='title' name='title' /> <input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' /> <input placeholder='url' name='url' type='url' required />
<button type='submit'>Submit</button> <button type='submit'>Submit</button>
<style jsx>{` <style jsx>{`
form { form {
...@@ -64,12 +52,23 @@ const createPost = gql` ...@@ -64,12 +52,23 @@ const createPost = gql`
export default graphql(createPost, { export default graphql(createPost, {
props: ({ mutate }) => ({ props: ({ mutate }) => ({
createPost: (title, url) => mutate({ createPost: (title, url) =>
variables: { title, url }, mutate({
update: (proxy, { data: { createPost } }) => { variables: { title, url },
const data = proxy.readQuery({ query: allPosts, variables: allPostsQueryVars }) update: (proxy, { data: { createPost } }) => {
proxy.writeQuery({ query: allPosts, data: {allPosts: [createPost, ...data.allPosts]}, variables: allPostsQueryVars }) const data = proxy.readQuery({
} query: allPosts,
}) variables: allPostsQueryVars
})
proxy.writeQuery({
query: allPosts,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
})
}
})
}) })
})(Submit) })(Submit)
...@@ -10,7 +10,7 @@ if (!process.browser) { ...@@ -10,7 +10,7 @@ if (!process.browser) {
global.fetch = fetch global.fetch = fetch
} }
function create (initialState) { function create(initialState) {
return new ApolloClient({ return new ApolloClient({
connectToDevTools: process.browser, connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
...@@ -18,11 +18,11 @@ function create (initialState) { ...@@ -18,11 +18,11 @@ function create (initialState) {
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute) uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers` credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers`
}), }),
cache: new InMemoryCache().restore(initialState || {}), cache: new InMemoryCache().restore(initialState || {})
}) })
} }
export default function initApollo (initialState) { export default function initApollo(initialState) {
// Make sure to create a new client for every server-side request so that data // Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad) // isn't shared between connections (which would be bad)
if (!process.browser) { if (!process.browser) {
......
...@@ -5,23 +5,25 @@ import Head from 'next/head' ...@@ -5,23 +5,25 @@ import Head from 'next/head'
import initApollo from './initApollo' import initApollo from './initApollo'
// Gets the display name of a JSX component for dev tools // Gets the display name of a JSX component for dev tools
function getComponentDisplayName (Component) { function getComponentDisplayName(Component) {
return Component.displayName || Component.name || 'Unknown' return Component.displayName || Component.name || 'Unknown'
} }
export default ComposedComponent => { export default ComposedComponent => {
return class WithData extends React.Component { return class WithData extends React.Component {
static displayName = `WithData(${getComponentDisplayName(ComposedComponent)})` static displayName = `WithData(${getComponentDisplayName(
ComposedComponent
)})`
static propTypes = { static propTypes = {
serverState: PropTypes.object.isRequired serverState: PropTypes.object.isRequired
} }
static async getInitialProps (ctx) { static async getInitialProps(ctx) {
// Initial serverState with apollo (empty) // Initial serverState with apollo (empty)
let serverState = { let serverState = {
apollo: { apollo: {
data: { } data: {}
} }
} }
// Evaluate the composed component's getInitialProps() // Evaluate the composed component's getInitialProps()
...@@ -34,14 +36,20 @@ export default ComposedComponent => { ...@@ -34,14 +36,20 @@ export default ComposedComponent => {
// and extract the resulting data // and extract the resulting data
if (!process.browser) { if (!process.browser) {
const apollo = initApollo() const apollo = initApollo()
// Provide the `url` prop data in case a GraphQL query uses it
const url = {query: ctx.query, pathname: ctx.pathname}
try { try {
// Run all GraphQL queries // Run all GraphQL queries
await getDataFromTree( await getDataFromTree(
<ApolloProvider client={apollo}> <ApolloProvider client={apollo}>
<ComposedComponent url={url} {...composedInitialProps} /> <ComposedComponent {...composedInitialProps} />
</ApolloProvider> </ApolloProvider>,
{
router: {
asPath: ctx.asPath,
pathname: ctx.pathname,
query: ctx.query
}
}
) )
} catch (error) { } catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR. // Prevent Apollo Client GraphQL errors from crashing SSR.
...@@ -66,12 +74,12 @@ export default ComposedComponent => { ...@@ -66,12 +74,12 @@ export default ComposedComponent => {
} }
} }
constructor (props) { constructor(props) {
super(props) super(props)
this.apollo = initApollo(this.props.serverState.apollo.data) this.apollo = initApollo(this.props.serverState.apollo.data)
} }
render () { render() {
return ( return (
<ApolloProvider client={this.apollo}> <ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} /> <ComposedComponent {...this.props} />
......
...@@ -7,16 +7,16 @@ ...@@ -7,16 +7,16 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"apollo-client-preset": "^1.0.1", "apollo-client-preset": "1.0.4",
"graphql": "^0.11.7", "graphql": "0.11.7",
"graphql-anywhere": "^3.1.0", "graphql-anywhere": "4.0.2",
"graphql-tag": "^2.5.0", "graphql-tag": "2.5.0",
"isomorphic-unfetch": "^2.0.0", "isomorphic-unfetch": "2.0.0",
"next": "latest", "next": "latest",
"prop-types": "^15.5.8", "prop-types": "15.6.0",
"react": "^16.0.0", "react": "16.2.0",
"react-apollo": "^2.0.0", "react-apollo": "2.0.1",
"react-dom": "^16.0.0" "react-dom": "16.2.0"
}, },
"author": "", "author": "",
"license": "ISC" "license": "ISC"
......
import App from '../components/App' import App from '../components/App'
import Header from '../components/Header' import Header from '../components/Header'
export default (props) => ( export default () => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<article> <article>
<h1>The Idea Behind This Example</h1> <h1>The Idea Behind This Example</h1>
<p> <p>
<a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that
allows you to easily query the exact data you need from a GraphQL
server. In addition to fetching and mutating data, Apollo analyzes your
queries and their results to construct a client-side cache of your data,
which is kept up to date as further queries and mutations are run,
fetching more results from the server.
</p> </p>
<p> <p>
In this simple example, we integrate Apollo seamlessly with <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages inside a <a href='https://facebook.github.io/react/docs/higher-order-components.html'>higher-order component (HOC)</a>. Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application. In this simple example, we integrate Apollo seamlessly with{' '}
<a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages
inside a{' '}
<a href='https://facebook.github.io/react/docs/higher-order-components.html'>
higher-order component (HOC)
</a>. Using the HOC pattern we're able to pass down a central store of
query result data created by Apollo into our React component hierarchy
defined inside each page of our Next application.
</p> </p>
<p> <p>
On initial page load, while on the server and inside getInitialProps, we invoke the Apollo method, <a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'>getDataFromTree</a>. This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. On initial page load, while on the server and inside getInitialProps, we
invoke the Apollo method,{' '}
<a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'>
getDataFromTree
</a>. This method returns a promise; at the point in which the promise
resolves, our Apollo Client store is completely initialized.
</p> </p>
<p> <p>
This example relies on <a href='http://graph.cool'>graph.cool</a> for its GraphQL backend. This example relies on <a href='http://graph.cool'>graph.cool</a> for
its GraphQL backend.
</p> </p>
</article> </article>
</App> </App>
......
...@@ -4,9 +4,9 @@ import Submit from '../components/Submit' ...@@ -4,9 +4,9 @@ import Submit from '../components/Submit'
import PostList from '../components/PostList' import PostList from '../components/PostList'
import withData from '../lib/withData' import withData from '../lib/withData'
export default withData((props) => ( export default withData(() => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header />
<Submit /> <Submit />
<PostList /> <PostList />
</App> </App>
......
...@@ -16,7 +16,7 @@ create-next-app --example with-asset-imports with-asset-imports-app ...@@ -16,7 +16,7 @@ create-next-app --example with-asset-imports with-asset-imports-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-asset-imports curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-asset-imports
cd with-asset-imports cd with-asset-imports
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-babel-macros with-babel-macros-app ...@@ -18,7 +18,7 @@ create-next-app --example with-babel-macros with-babel-macros-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-babel-macros curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-babel-macros
cd with-babel-macros cd with-babel-macros
``` ```
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-custom-babel-config curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-custom-babel-config
cd with-custom-babel-config cd with-custom-babel-config
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-cxs with-cxs-app ...@@ -18,7 +18,7 @@ create-next-app --example with-cxs with-cxs-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-cxs curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-cxs
cd with-cxs cd with-cxs
``` ```
......
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-data-prefetch)
# Example app with prefetching data
## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-data-prefetch with-data-prefetch-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-data-prefetch
cd with-data-prefetch
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
Next.js lets you prefetch the JS code of another page just adding the `prefetch` prop to `next/link`. This can help you avoid the download time a new page you know beforehand the user is most probably going to visit.
In the example we'll extend the `Link` component to also run the `getInitialProps` (if it's defined) of the new page and save the resulting props on cache. When the user visits the page it will load the props from cache and avoid any request.
It uses `sessionStorage` as cache but it could be replaced with any other more specialized system. Like IndexedDB or just an in-memory API with a better cache strategy to prune old cache and force new fetching.
> This example is based on the [ScaleAPI article explaining this same technique](https://www.scaleapi.com/blog/increasing-the-performance-of-dynamic-next-js-websites).
**Note**: it only works in production environment. In development Next.js just avoid doing the prefetch.
import PropTypes from 'prop-types'
import Link from 'next/link'
import Router from 'next/router'
import { execOnce, warn } from 'next/dist/lib/utils'
import exact from 'prop-types-exact'
import { format, resolve, parse } from 'url'
// extend default next/link to customize the prefetch behaviour
export default class LinkWithData extends Link {
// re defined Link propTypes to add `withData`
static propTypes = exact({
href: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
as: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
prefetch: PropTypes.bool,
replace: PropTypes.bool,
shallow: PropTypes.bool,
passHref: PropTypes.bool,
scroll: PropTypes.bool,
children: PropTypes.oneOfType([
PropTypes.element,
(props, propName) => {
const value = props[propName]
if (typeof value === 'string') {
execOnce(warn)(`Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>`)
}
return null
}
]).isRequired,
withData: PropTypes.bool // our custom prop
});
// our custom prefetch method
async prefetch () {
// if the prefetch prop is not defined or
// we're running server side do nothing
if (!this.props.prefetch) return
if (typeof window === 'undefined') return
const url =
typeof this.props.href !== 'string'
? format(this.props.href)
: this.props.href
const { pathname } = window.location
const href = resolve(pathname, url)
const { query } =
typeof this.props.href !== 'string'
? this.props.href
: parse(url, true)
const Component = await Router.prefetch(href)
// if withData prop is defined, Component exists and has getInitialProps
// fetch the component props (the component should save it in cache)
if (this.props.withData && Component && Component.getInitialProps) {
const ctx = { pathname: href, query, isVirtualCall: true }
await Component.getInitialProps(ctx)
}
}
}
{
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "^2.0.0",
"next": "^4.2.0",
"prop-types": "^15.6.0",
"prop-types-exact": "^1.1.1",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
import { Component } from 'react'
import fetch from 'isomorphic-unfetch'
import { format } from 'url'
export default class Article extends Component {
static async getInitialProps ({ req, query, pathname, isVirtualCall }) {
const url = format({ pathname, query })
// if we're not running server side
// get the props from sessionStorage using the pathname + query as key
// if we got something return it as an object
if (!req) {
const props = window.sessionStorage.getItem(url)
if (props) {
return JSON.parse(props)
}
}
// fetch data as usual
const responses = await Promise.all([
fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`),
fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}/comments`)
])
const [article, comments] = await Promise.all(
responses.map(response => response.json())
)
const user = await fetch(
`https://jsonplaceholder.typicode.com/users/${article.userId}`
).then(response => response.json())
const props = { article, comments, user }
// if the method is being called by our Link component
// save props on sessionStorage using the full url (pathname + query)
// as key and the serialized props as value
if (isVirtualCall) {
window.sessionStorage.setItem(url, JSON.stringify(props))
}
return props
}
render () {
const { article, comments, user } = this.props
return (
<div>
<h1>{article.title}</h1>
<div>
<a href={`mailto:${user.email}`}>{user.name}</a>
</div>
<p>{article.body}</p>
<ul>
{comments.map(comment => (
<li key={comment.id}>
{comment.body}
<br />
By <strong>{comment.name}</strong>
</li>
))}
</ul>
</div>
)
}
}
import Link from '../components/link'
// we just render a list of 3 articles having 2 with prefetched data
export default () => (
<main>
<h1>Next.js - with data prefetch example</h1>
<ul>
<li>
<Link href='/article?id=1' prefetch withData>
<a>Article 1</a>
</Link>
</li>
<li>
<Link href='/article?id=2' prefetch>
<a>Article 2</a>
</Link>
</li>
<li>
<Link href='/article?id=3' prefetch withData>
<a>Article 3</a>
</Link>
</li>
</ul>
</main>
)
...@@ -18,7 +18,7 @@ create-next-app --example with-dotenv with-dotenv-app ...@@ -18,7 +18,7 @@ create-next-app --example with-dotenv with-dotenv-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-dotenv curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-dotenv
cd with-dotenv cd with-dotenv
``` ```
......
...@@ -16,7 +16,7 @@ create-next-app --example with-dynamic-import with-dynamic-import-app ...@@ -16,7 +16,7 @@ create-next-app --example with-dynamic-import with-dynamic-import-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-dynamic-import curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-dynamic-import
cd with-dynamic-import cd with-dynamic-import
``` ```
......
...@@ -18,7 +18,7 @@ create-next-app --example with-electron with-electron-app ...@@ -18,7 +18,7 @@ create-next-app --example with-electron with-electron-app
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-electron curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-electron
cd with-electron cd with-electron
``` ```
......
import {Basic, Combined, Animated, bounce} from '../shared/styles'
const Home = () => (
<div>
<Basic>Cool Styles</Basic>
<Combined>
With <code>:hover</code>.
</Combined>
<Animated animation={bounce}>Let's bounce.</Animated>
</div>
)
export default Home
import React, { Component } from 'react'
import { hydrate } from 'react-emotion'
import { injectGlobalStyles } from '../shared/styles'
const withEmotion = ComposedComponent => {
class HOC extends Component {
componentWillMount () {
if (typeof window !== 'undefined') {
hydrate(window.__NEXT_DATA__.ids)
}
injectGlobalStyles()
}
render () {
return <ComposedComponent />
}
};
return HOC
}
export default withEmotion
{
"name": "with-emotion-fiber",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next"
},
"keywords": [],
"author": "Thomas Greco",
"license": "ISC",
"dependencies": {
"emotion": "^8.0.11",
"emotion-server": "^8.0.11",
"next": "^4.1.4",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"react-emotion": "^8.0.11"
}
}
import Document, { Head, Main, NextScript } from 'next/document'
import { extractCritical } from 'emotion-server'
export default class MyDocument extends Document {
static getInitialProps ({ renderPage }) {
const page = renderPage()
const styles = extractCritical(page.html)
return { ...page, ...styles }
}
constructor (props) {
super(props)
const { __NEXT_DATA__, ids } = props
if (ids) {
__NEXT_DATA__.ids = ids
}
}
render () {
return (
<html>
<Head>
<title>With Emotion</title>
<style dangerouslySetInnerHTML={{ __html: this.props.css }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
import withEmotion from '../hoc/withEmotion.component'
import home from '../features/home.component'
export default withEmotion(home)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment