Commit 1765007a authored by Rafael Almeida's avatar Rafael Almeida Committed by Luis Fernando Alvarez D

Update with-apollo example with hooks (#8363)

* Add @apollo/react-hooks and @apollo/react-ssr

* Migrate react-apollo to @apollo/react-hooks and Query component

* Migrate direct client mutations to useMutation hook

* Disable submit button when submiting a new post

* Fix Show More button not updating when loading more entries

* All queries with uppercase name

* Remove react-apollo

* Update getDataFromTree links

* Fixed lint issues
parent a7baeb04
......@@ -47,9 +47,9 @@ now
In this simple example, we integrate Apollo seamlessly with Next by wrapping our _pages/\_app.js_ inside a [higher-order component (HOC)](https://facebook.github.io/react/docs/higher-order-components.html). 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.
On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree). 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, [`getDataFromTree`](https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.
This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend.
Note: Do not be alarmed that you see two renders being executed. Apollo recursively traverses the React render tree looking for Apollo query components. When it has done that, it fetches all these queries and then passes the result to a cache. This cache is then used to render the data on the server side (another React render).
https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree
https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree
......@@ -29,10 +29,13 @@ export default ({ children }) => (
color: white;
display: flex;
padding: 5px 7px;
transition: background-color 0.3s;
}
button:active {
background-color: #1b9db7;
transition: background-color 0.3s;
}
button:disabled {
background-color: #b5bebf;
}
button:focus {
outline: none;
......
import { Query } from 'react-apollo'
import { useQuery } from '@apollo/react-hooks'
import { NetworkStatus } from 'apollo-boost'
import gql from 'graphql-tag'
import ErrorMessage from './ErrorMessage'
import PostUpvoter from './PostUpvoter'
export const allPostsQuery = gql`
export const ALL_POSTS_QUERY = gql`
query allPosts($first: Int!, $skip: Int!) {
allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) {
id
......@@ -23,92 +24,98 @@ export const allPostsQueryVars = {
}
export default function PostList () {
return (
<Query query={allPostsQuery} variables={allPostsQueryVars}>
{({ loading, error, data: { allPosts, _allPostsMeta }, fetchMore }) => {
if (error) return <ErrorMessage message='Error loading posts.' />
if (loading) return <div>Loading</div>
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
<section>
<ul>
{allPosts.map((post, index) => (
<li key={post.id}>
<div>
<span>{index + 1}. </span>
<a href={post.url}>{post.title}</a>
<PostUpvoter id={post.id} votes={post.votes} />
</div>
</li>
))}
</ul>
{areMorePosts ? (
<button onClick={() => loadMorePosts(allPosts, fetchMore)}>
{' '}
{loading ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{`
section {
padding-bottom: 20px;
}
li {
display: block;
margin-bottom: 10px;
}
div {
align-items: center;
display: flex;
}
a {
font-size: 14px;
margin-right: 10px;
text-decoration: none;
padding-bottom: 0;
border: 0;
}
span {
font-size: 14px;
margin-right: 5px;
}
ul {
margin: 0;
padding: 0;
}
button:before {
align-self: center;
border-style: solid;
border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent;
content: '';
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</section>
)
}}
</Query>
const { loading, error, data, fetchMore, networkStatus } = useQuery(
ALL_POSTS_QUERY,
{
variables: allPostsQueryVars,
// Setting this value to true will make the component rerender when
// the "networkStatus" changes, so we are able to know if it is fetching
// more data
notifyOnNetworkStatusChange: true
}
)
}
function loadMorePosts (allPosts, fetchMore) {
fetchMore({
variables: {
skip: allPosts.length
},
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult
const loadingMorePosts = networkStatus === NetworkStatus.fetchMore
const loadMorePosts = () => {
fetchMore({
variables: {
skip: allPosts.length
},
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult
}
return Object.assign({}, previousResult, {
// Append the new posts results to the old one
allPosts: [...previousResult.allPosts, ...fetchMoreResult.allPosts]
})
}
return Object.assign({}, previousResult, {
// Append the new posts results to the old one
allPosts: [...previousResult.allPosts, ...fetchMoreResult.allPosts]
})
}
})
})
}
if (error) return <ErrorMessage message='Error loading posts.' />
if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
<section>
<ul>
{allPosts.map((post, index) => (
<li key={post.id}>
<div>
<span>{index + 1}. </span>
<a href={post.url}>{post.title}</a>
<PostUpvoter id={post.id} votes={post.votes} />
</div>
</li>
))}
</ul>
{areMorePosts && (
<button onClick={() => loadMorePosts()} disabled={loadingMorePosts}>
{loadingMorePosts ? 'Loading...' : 'Show More'}
</button>
)}
<style jsx>{`
section {
padding-bottom: 20px;
}
li {
display: block;
margin-bottom: 10px;
}
div {
align-items: center;
display: flex;
}
a {
font-size: 14px;
margin-right: 10px;
text-decoration: none;
padding-bottom: 0;
border: 0;
}
span {
font-size: 14px;
margin-right: 5px;
}
ul {
margin: 0;
padding: 0;
}
button:before {
align-self: center;
border-style: solid;
border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent;
content: '';
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</section>
)
}
import React from 'react'
import { ApolloConsumer } from 'react-apollo'
import { useMutation } from '@apollo/react-hooks'
import gql from 'graphql-tag'
const UPDATE_POST_MUTATION = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
__typename
id
votes
}
}
`
export default function PostUpvoter ({ votes, id }) {
return (
<ApolloConsumer>
{client => (
<button onClick={() => upvotePost(votes, id, client)}>
{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>
)}
</ApolloConsumer>
)
}
const [updatePost] = useMutation(UPDATE_POST_MUTATION)
function upvotePost (votes, id, client) {
client.mutate({
mutation: gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`,
variables: {
id,
votes: votes + 1
},
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
const upvotePost = () => {
updatePost({
variables: {
id,
votes: votes + 1
},
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id,
votes: votes + 1
}
}
}
})
})
}
return (
<button onClick={() => upvotePost()}>
{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>
)
}
import { ApolloConsumer } from 'react-apollo'
import { useMutation } from '@apollo/react-hooks'
import gql from 'graphql-tag'
import { allPostsQuery, allPostsQueryVars } from './PostList'
import { ALL_POSTS_QUERY, allPostsQueryVars } from './PostList'
const CREATE_POST_MUTATION = gql`
mutation createPost($title: String!, $url: String!) {
createPost(title: $title, url: $url) {
id
title
votes
url
createdAt
}
}
`
export default function Submit () {
return (
<ApolloConsumer>
{client => (
<form onSubmit={event => handleSubmit(event, client)}>
<h1>Submit</h1>
<input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' type='url' required />
<button type='submit'>Submit</button>
<style jsx>{`
form {
border-bottom: 1px solid #ececec;
padding-bottom: 20px;
margin-bottom: 20px;
}
h1 {
font-size: 20px;
}
input {
display: block;
margin-bottom: 10px;
}
`}</style>
</form>
)}
</ApolloConsumer>
)
}
const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
function handleSubmit (event, client) {
event.preventDefault()
const form = event.target
const formData = new window.FormData(form)
const title = formData.get('title')
const url = formData.get('url')
form.reset()
const handleSubmit = event => {
event.preventDefault()
const form = event.target
const formData = new window.FormData(form)
const title = formData.get('title')
const url = formData.get('url')
form.reset()
client.mutate({
mutation: gql`
mutation createPost($title: String!, $url: String!) {
createPost(title: $title, url: $url) {
id
title
votes
url
createdAt
}
createPost({
variables: { title, url },
update: (proxy, { data: { createPost } }) => {
const data = proxy.readQuery({
query: ALL_POSTS_QUERY,
variables: allPostsQueryVars
})
// Update the cache with the new post at the top of the
proxy.writeQuery({
query: ALL_POSTS_QUERY,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
})
}
`,
variables: { title, url },
update: (proxy, { data: { createPost } }) => {
const data = proxy.readQuery({
query: allPostsQuery,
variables: allPostsQueryVars
})
proxy.writeQuery({
query: allPostsQuery,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
})
}
})
})
}
return (
<form onSubmit={handleSubmit}>
<h1>Submit</h1>
<input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' type='url' required />
<button type='submit' disabled={loading}>
Submit
</button>
<style jsx>{`
form {
border-bottom: 1px solid #ececec;
padding-bottom: 20px;
margin-bottom: 20px;
}
h1 {
font-size: 20px;
}
input {
display: block;
margin-bottom: 10px;
}
`}</style>
</form>
)
}
import React from 'react'
import initApollo from './init-apollo'
import Head from 'next/head'
import { getDataFromTree } from 'react-apollo'
import { getDataFromTree } from '@apollo/react-ssr'
export default App => {
return class Apollo extends React.Component {
......
......@@ -7,13 +7,14 @@
"start": "next start"
},
"dependencies": {
"apollo-boost": "^0.1.16",
"@apollo/react-hooks": "3.0.0",
"@apollo/react-ssr": "3.0.0",
"apollo-boost": "0.4.4",
"graphql": "^14.0.2",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"prop-types": "^15.6.2",
"react": "^16.7.0",
"react-apollo": "^2.1.11",
"react-dom": "^16.7.0"
},
"author": "",
......
import App from 'next/app'
import React from 'react'
import { ApolloProvider } from '@apollo/react-hooks'
import withApolloClient from '../lib/with-apollo-client'
import { ApolloProvider } from 'react-apollo'
class MyApp extends App {
render () {
......
......@@ -16,7 +16,7 @@ export default () => (
</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
<a href='https://github.com/zeit/next.js'>Next</a> by wrapping our App component
inside a{' '}
<a href='https://facebook.github.io/react/docs/higher-order-components.html'>
higher-order component (HOC)
......@@ -28,7 +28,7 @@ export default () => (
<p>
On initial page load, while on the server and inside getInitialProps, we
invoke the Apollo method,{' '}
<a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'>
<a href='https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree'>
getDataFromTree
</a>
. This method returns a promise; at the point in which the promise
......
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