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