Commit 718e5771 authored by Stanislav Morozevich's avatar Stanislav Morozevich Committed by Joe Haddad

Update with-apollo-auth example (#8416)

* Provide default value for apolloState

* Use hooks api

* Fix formatting problems

* Use useRef hook

* Add simple comment about displayName

* Go with caret for react-hooks and react-ssr
parent a8aa15af
import { Mutation, withApollo } from 'react-apollo' import { useRef } from 'react'
import { useMutation, useApolloClient } from '@apollo/react-hooks'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import cookie from 'cookie' import cookie from 'cookie'
import redirect from '../lib/redirect' import redirect from '../lib/redirect'
...@@ -17,76 +18,62 @@ const CREATE_USER = gql` ...@@ -17,76 +18,62 @@ const CREATE_USER = gql`
} }
` `
const RegisterBox = ({ client }) => { const RegisterBox = () => {
let name, email, password const client = useApolloClient()
const onCompleted = data => {
// Store the token in cookie
document.cookie = cookie.serialize('token', data.signinUser.token, {
maxAge: 30 * 24 * 60 * 60 // 30 days
})
// Force a reload of all the current queries now that the user is
// logged in
client.cache.reset().then(() => {
redirect({}, '/')
})
}
const onError = error => {
// If you want to send error to external service?
console.error(error)
}
const [create, { error }] = useMutation(CREATE_USER, { onCompleted, onError })
const name = useRef(null)
const email = useRef(null)
const password = useRef(null)
return ( return (
<Mutation <form
mutation={CREATE_USER} onSubmit={e => {
onCompleted={data => { e.preventDefault()
// Store the token in cookie e.stopPropagation()
document.cookie = cookie.serialize('token', data.signinUser.token, {
maxAge: 30 * 24 * 60 * 60 // 30 days create({
}) variables: {
// Force a reload of all the current queries now that the user is name: name.current.value,
// logged in email: email.current.value,
client.cache.reset().then(() => { password: password.current.value
redirect({}, '/') }
}) })
}}
onError={error => { name.current.value = email.current.value = password.current.value = ''
// If you want to send error to external service?
console.log(error)
}} }}
> >
{(create, { data, error }) => ( {error && <p>Issue occurred while registering :(</p>}
<form <input name='name' placeholder='Name' ref={name} />
onSubmit={e => { <br />
e.preventDefault() <input name='email' placeholder='Email' ref={email} />
e.stopPropagation() <br />
<input
create({ name='password'
variables: { placeholder='Password'
name: name.value, ref={password}
email: email.value, type='password'
password: password.value />
} <br />
}) <button>Register</button>
</form>
name.value = email.value = password.value = ''
}}
>
{error && <p>Issue occurred while registering :(</p>}
<input
name='name'
placeholder='Name'
ref={node => {
name = node
}}
/>
<br />
<input
name='email'
placeholder='Email'
ref={node => {
email = node
}}
/>
<br />
<input
name='password'
placeholder='Password'
ref={node => {
password = node
}}
type='password'
/>
<br />
<button>Register</button>
</form>
)}
</Mutation>
) )
} }
export default withApollo(RegisterBox) export default RegisterBox
import { Mutation, withApollo } from 'react-apollo' import { useRef } from 'react'
import { useMutation, useApolloClient } from '@apollo/react-hooks'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import cookie from 'cookie' import cookie from 'cookie'
import redirect from '../lib/redirect' import redirect from '../lib/redirect'
...@@ -12,67 +13,63 @@ const SIGN_IN = gql` ...@@ -12,67 +13,63 @@ const SIGN_IN = gql`
` `
// TODO: Find a better name for component. // TODO: Find a better name for component.
const SigninBox = ({ client }) => { const SigninBox = () => {
let email, password const client = useApolloClient()
const onCompleted = data => {
// Store the token in cookie
document.cookie = cookie.serialize('token', data.signinUser.token, {
maxAge: 30 * 24 * 60 * 60 // 30 days
})
// Force a reload of all the current queries now that the user is
// logged in
client.cache.reset().then(() => {
redirect({}, '/')
})
}
const onError = error => {
// If you want to send error to external service?
console.error(error)
}
const [signinUser, { error }] = useMutation(SIGN_IN, {
onCompleted,
onError
})
const email = useRef(null)
const password = useRef(null)
return ( return (
<Mutation <form
mutation={SIGN_IN} onSubmit={e => {
onCompleted={data => { e.preventDefault()
// Store the token in cookie e.stopPropagation()
document.cookie = cookie.serialize('token', data.signinUser.token, {
maxAge: 30 * 24 * 60 * 60 // 30 days signinUser({
}) variables: {
// Force a reload of all the current queries now that the user is email: email.current.value,
// logged in password: password.current.value
client.cache.reset().then(() => { }
redirect({}, '/')
}) })
}}
onError={error => { email.current.value = password.current.value = ''
// If you want to send error to external service?
console.log(error)
}} }}
> >
{(signinUser, { data, error }) => ( {error && <p>No user found with that information.</p>}
<form <input name='email' placeholder='Email' ref={email} />
onSubmit={e => { <br />
e.preventDefault() <input
e.stopPropagation() name='password'
placeholder='Password'
signinUser({ ref={password}
variables: { type='password'
email: email.value, />
password: password.value <br />
} <button>Sign in</button>
}) </form>
email.value = password.value = ''
}}
>
{error && <p>No user found with that information.</p>}
<input
name='email'
placeholder='Email'
ref={node => {
email = node
}}
/>
<br />
<input
name='password'
placeholder='Password'
ref={node => {
password = node
}}
type='password'
/>
<br />
<button>Sign in</button>
</form>
)}
</Mutation>
) )
} }
export default withApollo(SigninBox) export default SigninBox
import React from 'react' import React from 'react'
import cookie from 'cookie' import cookie from 'cookie'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { getDataFromTree } from 'react-apollo' import { getDataFromTree } from '@apollo/react-ssr'
import Head from 'next/head' import Head from 'next/head'
import initApollo from './initApollo' import initApollo from './initApollo'
...@@ -12,7 +12,15 @@ function parseCookies (req, options = {}) { ...@@ -12,7 +12,15 @@ function parseCookies (req, options = {}) {
export default App => { export default App => {
return class WithData extends React.Component { return class WithData extends React.Component {
// It is needed for better devtools experience. Check how react devtools shows it: "MyApp WithData"
static displayName = `WithData(${App.displayName})` static displayName = `WithData(${App.displayName})`
// Since apolloState is required but it is missed before this method returns the new props,
// so it is needed to provide defaults
static defaultProps = {
apolloState: {}
}
static propTypes = { static propTypes = {
apolloState: PropTypes.object.isRequired apolloState: PropTypes.object.isRequired
} }
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@apollo/react-hooks": "^3.0.1",
"@apollo/react-ssr": "^3.0.1",
"apollo-boost": "^0.1.6", "apollo-boost": "^0.1.6",
"apollo-link-context": "^1.0.8", "apollo-link-context": "^1.0.8",
"cookie": "^0.3.1", "cookie": "^0.3.1",
...@@ -18,7 +20,6 @@ ...@@ -18,7 +20,6 @@
"next": "latest", "next": "latest",
"prop-types": "^15.6.1", "prop-types": "^15.6.1",
"react": "^16.7.0", "react": "^16.7.0",
"react-apollo": "^2.1.4",
"react-dom": "^16.7.0" "react-dom": "^16.7.0"
} }
} }
import App from 'next/app' import App from 'next/app'
import React from 'react' import React from 'react'
import { ApolloProvider } from 'react-apollo' import { ApolloProvider } from '@apollo/react-hooks'
import withApollo from '../lib/withApollo' import withApollo from '../lib/withApollo'
class MyApp extends App { class MyApp extends App {
static displayName = 'MyApp'
render () { render () {
const { Component, pageProps, apolloClient } = this.props const { Component, pageProps, apolloClient } = this.props
return ( return (
......
...@@ -21,7 +21,7 @@ export default class CreateAccount extends React.Component { ...@@ -21,7 +21,7 @@ export default class CreateAccount extends React.Component {
render () { render () {
return ( return (
<React.Fragment> <>
{/* RegisterBox handles all register logic. */} {/* RegisterBox handles all register logic. */}
<RegisterBox /> <RegisterBox />
<hr /> <hr />
...@@ -29,7 +29,7 @@ export default class CreateAccount extends React.Component { ...@@ -29,7 +29,7 @@ export default class CreateAccount extends React.Component {
<Link prefetch href='/signin'> <Link prefetch href='/signin'>
<a>Sign in</a> <a>Sign in</a>
</Link> </Link>
</React.Fragment> </>
) )
} }
} }
import React from 'react' import React from 'react'
import cookie from 'cookie' import cookie from 'cookie'
import { ApolloConsumer } from 'react-apollo' import { useApolloClient } from '@apollo/react-hooks'
import redirect from '../lib/redirect' import redirect from '../lib/redirect'
import checkLoggedIn from '../lib/checkLoggedIn' import checkLoggedIn from '../lib/checkLoggedIn'
export default class Index extends React.Component { const Index = ({ loggedInUser }) => {
static async getInitialProps (context, apolloClient) { const apolloClient = useApolloClient()
const { loggedInUser } = await checkLoggedIn(context.apolloClient)
if (!loggedInUser.user) { const signout = () => {
// If not signed in, send them somewhere more useful
redirect(context, '/signin')
}
return { loggedInUser }
}
signout = apolloClient => () => {
document.cookie = cookie.serialize('token', '', { document.cookie = cookie.serialize('token', '', {
maxAge: -1 // Expire the cookie immediately maxAge: -1 // Expire the cookie immediately
}) })
...@@ -30,16 +21,23 @@ export default class Index extends React.Component { ...@@ -30,16 +21,23 @@ export default class Index extends React.Component {
}) })
} }
render () { return (
return ( <div>
<ApolloConsumer> Hello {loggedInUser.user.name}!<br />
{client => ( <button onClick={signout}>Sign out</button>
<div> </div>
Hello {this.props.loggedInUser.user.name}!<br /> )
<button onClick={this.signout(client)}>Sign out</button> }
</div>
)} Index.getInitialProps = async context => {
</ApolloConsumer> const { loggedInUser } = await checkLoggedIn(context.apolloClient)
)
if (!loggedInUser.user) {
// If not signed in, send them somewhere more useful
redirect(context, '/signin')
} }
return { loggedInUser }
} }
export default Index
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