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,13 +24,42 @@ export const allPostsQueryVars = { ...@@ -23,13 +24,42 @@ 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 }) => { {
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
}
)
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]
})
}
})
}
if (error) return <ErrorMessage message='Error loading posts.' /> if (error) return <ErrorMessage message='Error loading posts.' />
if (loading) return <div>Loading</div> if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
<section> <section>
<ul> <ul>
...@@ -43,13 +73,10 @@ export default function PostList () { ...@@ -43,13 +73,10 @@ export default function PostList () {
</li> </li>
))} ))}
</ul> </ul>
{areMorePosts ? ( {areMorePosts && (
<button onClick={() => loadMorePosts(allPosts, fetchMore)}> <button onClick={() => loadMorePosts()} disabled={loadingMorePosts}>
{' '} {loadingMorePosts ? 'Loading...' : 'Show More'}
{loading ? 'Loading...' : 'Show More'}{' '}
</button> </button>
) : (
''
)} )}
<style jsx>{` <style jsx>{`
section { section {
...@@ -91,24 +118,4 @@ export default function PostList () { ...@@ -91,24 +118,4 @@ export default function PostList () {
`}</style> `}</style>
</section> </section>
) )
}}
</Query>
)
}
function loadMorePosts (allPosts, fetchMore) {
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]
})
}
})
} }
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 }) {
const [updatePost] = useMutation(UPDATE_POST_MUTATION)
const upvotePost = () => {
updatePost({
variables: {
id,
votes: votes + 1
},
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id,
votes: votes + 1
}
}
})
}
return ( return (
<ApolloConsumer> <button onClick={() => upvotePost()}>
{client => (
<button onClick={() => upvotePost(votes, id, client)}>
{votes} {votes}
<style jsx>{` <style jsx>{`
button { button {
...@@ -29,33 +56,5 @@ export default function PostUpvoter ({ votes, id }) { ...@@ -29,33 +56,5 @@ export default function PostUpvoter ({ votes, id }) {
} }
`}</style> `}</style>
</button> </button>
)}
</ApolloConsumer>
) )
} }
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',
id,
votes: votes + 1
}
}
})
}
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'
export default function Submit () { const CREATE_POST_MUTATION = gql`
return ( mutation createPost($title: String!, $url: String!) {
<ApolloConsumer> createPost(title: $title, url: $url) {
{client => ( id
<form onSubmit={event => handleSubmit(event, client)}> title
<h1>Submit</h1> votes
<input placeholder='title' name='title' type='text' required /> url
<input placeholder='url' name='url' type='url' required /> createdAt
<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) { export default function Submit () {
const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
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)
...@@ -39,26 +25,16 @@ function handleSubmit (event, client) { ...@@ -39,26 +25,16 @@ function handleSubmit (event, client) {
const url = formData.get('url') const url = formData.get('url')
form.reset() form.reset()
client.mutate({ createPost({
mutation: gql`
mutation createPost($title: String!, $url: String!) {
createPost(title: $title, url: $url) {
id
title
votes
url
createdAt
}
}
`,
variables: { title, url }, variables: { title, url },
update: (proxy, { data: { createPost } }) => { update: (proxy, { data: { createPost } }) => {
const data = proxy.readQuery({ const data = proxy.readQuery({
query: allPostsQuery, query: ALL_POSTS_QUERY,
variables: allPostsQueryVars variables: allPostsQueryVars
}) })
// Update the cache with the new post at the top of the
proxy.writeQuery({ proxy.writeQuery({
query: allPostsQuery, query: ALL_POSTS_QUERY,
data: { data: {
...data, ...data,
allPosts: [createPost, ...data.allPosts] allPosts: [createPost, ...data.allPosts]
...@@ -67,4 +43,30 @@ function handleSubmit (event, client) { ...@@ -67,4 +43,30 @@ function handleSubmit (event, client) {
}) })
} }
}) })
}
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 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