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 ...@@ -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. 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. 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). 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 }) => ( ...@@ -29,10 +29,13 @@ export default ({ children }) => (
color: white; color: white;
display: flex; display: flex;
padding: 5px 7px; padding: 5px 7px;
transition: background-color 0.3s;
} }
button:active { button:active {
background-color: #1b9db7; background-color: #1b9db7;
transition: background-color 0.3s; }
button:disabled {
background-color: #b5bebf;
} }
button:focus { button:focus {
outline: none; outline: none;
......
import { Query } from 'react-apollo' import { useQuery } from '@apollo/react-hooks'
import { NetworkStatus } from 'apollo-boost'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import ErrorMessage from './ErrorMessage' import ErrorMessage from './ErrorMessage'
import PostUpvoter from './PostUpvoter' import PostUpvoter from './PostUpvoter'
export const allPostsQuery = gql` export const ALL_POSTS_QUERY = 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
...@@ -23,92 +24,98 @@ export const allPostsQueryVars = { ...@@ -23,92 +24,98 @@ export const allPostsQueryVars = {
} }
export default function PostList () { export default function PostList () {
return ( const { loading, error, data, fetchMore, networkStatus } = useQuery(
<Query query={allPostsQuery} variables={allPostsQueryVars}> ALL_POSTS_QUERY,
{({ loading, error, data: { allPosts, _allPostsMeta }, fetchMore }) => { {
if (error) return <ErrorMessage message='Error loading posts.' /> variables: allPostsQueryVars,
if (loading) return <div>Loading</div> // Setting this value to true will make the component rerender when
// the "networkStatus" changes, so we are able to know if it is fetching
const areMorePosts = allPosts.length < _allPostsMeta.count // more data
return ( notifyOnNetworkStatusChange: true
<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>
) )
}
function loadMorePosts (allPosts, fetchMore) { const loadingMorePosts = networkStatus === NetworkStatus.fetchMore
fetchMore({
variables: { const loadMorePosts = () => {
skip: allPosts.length fetchMore({
}, variables: {
updateQuery: (previousResult, { fetchMoreResult }) => { skip: allPosts.length
if (!fetchMoreResult) { },
return previousResult 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 React from 'react'
import { ApolloConsumer } from 'react-apollo' import { useMutation } from '@apollo/react-hooks'
import gql from 'graphql-tag' 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 }) { export default function PostUpvoter ({ votes, id }) {
return ( const [updatePost] = useMutation(UPDATE_POST_MUTATION)
<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>
)
}
function upvotePost (votes, id, client) { const upvotePost = () => {
client.mutate({ updatePost({
mutation: gql` variables: {
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',
id, id,
votes: votes + 1 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 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 () { export default function Submit () {
return ( const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
<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>
)
}
function handleSubmit (event, client) { const handleSubmit = event => {
event.preventDefault() event.preventDefault()
const form = event.target const form = event.target
const formData = new window.FormData(form) const formData = new window.FormData(form)
const title = formData.get('title') const title = formData.get('title')
const url = formData.get('url') const url = formData.get('url')
form.reset() form.reset()
client.mutate({ createPost({
mutation: gql` variables: { title, url },
mutation createPost($title: String!, $url: String!) { update: (proxy, { data: { createPost } }) => {
createPost(title: $title, url: $url) { const data = proxy.readQuery({
id query: ALL_POSTS_QUERY,
title variables: allPostsQueryVars
votes })
url // Update the cache with the new post at the top of the
createdAt 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({ return (
query: allPostsQuery, <form onSubmit={handleSubmit}>
variables: allPostsQueryVars <h1>Submit</h1>
}) <input placeholder='title' name='title' type='text' required />
proxy.writeQuery({ <input placeholder='url' name='url' type='url' required />
query: allPostsQuery, <button type='submit' disabled={loading}>
data: { Submit
...data, </button>
allPosts: [createPost, ...data.allPosts] <style jsx>{`
}, form {
variables: allPostsQueryVars 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 React from 'react'
import initApollo from './init-apollo' import initApollo from './init-apollo'
import Head from 'next/head' import Head from 'next/head'
import { getDataFromTree } from 'react-apollo' import { getDataFromTree } from '@apollo/react-ssr'
export default App => { export default App => {
return class Apollo extends React.Component { return class Apollo extends React.Component {
......
...@@ -7,13 +7,14 @@ ...@@ -7,13 +7,14 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "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", "graphql": "^14.0.2",
"isomorphic-unfetch": "^3.0.0", "isomorphic-unfetch": "^3.0.0",
"next": "latest", "next": "latest",
"prop-types": "^15.6.2", "prop-types": "^15.6.2",
"react": "^16.7.0", "react": "^16.7.0",
"react-apollo": "^2.1.11",
"react-dom": "^16.7.0" "react-dom": "^16.7.0"
}, },
"author": "", "author": "",
......
import App from 'next/app' import App from 'next/app'
import React from 'react' import React from 'react'
import { ApolloProvider } from '@apollo/react-hooks'
import withApolloClient from '../lib/with-apollo-client' import withApolloClient from '../lib/with-apollo-client'
import { ApolloProvider } from 'react-apollo'
class MyApp extends App { class MyApp extends App {
render () { render () {
......
...@@ -16,7 +16,7 @@ export default () => ( ...@@ -16,7 +16,7 @@ export default () => (
</p> </p>
<p> <p>
In this simple example, we integrate Apollo seamlessly with{' '} 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{' '} inside a{' '}
<a href='https://facebook.github.io/react/docs/higher-order-components.html'> <a href='https://facebook.github.io/react/docs/higher-order-components.html'>
higher-order component (HOC) higher-order component (HOC)
...@@ -28,7 +28,7 @@ export default () => ( ...@@ -28,7 +28,7 @@ export default () => (
<p> <p>
On initial page load, while on the server and inside getInitialProps, we On initial page load, while on the server and inside getInitialProps, we
invoke the Apollo method,{' '} 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 getDataFromTree
</a> </a>
. This method returns a promise; at the point in which the promise . 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