Skip to content

Commit 24ce59f

Browse files
authored
Merge pull request #4200 from denny-ddfe/patch-1
Part8d: Refactor LoginForm component
2 parents 3cc0e9d + ceda906 commit 24ce59f

File tree

1 file changed

+8
-15
lines changed

1 file changed

+8
-15
lines changed

src/content/8/en/part8d.md

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -54,34 +54,30 @@ The *LoginForm* component works pretty much just like all the other components d
5454
Interesting lines in the code have been highlighted:
5555

5656
```js
57-
import { useState, useEffect } from 'react'
57+
import { useState } from 'react'
5858
import { useMutation } from '@apollo/client/react'
5959
import { LOGIN } from '../queries'
6060

6161
const LoginForm = ({ setError, setToken }) => {
6262
const [username, setUsername] = useState('')
6363
const [password, setPassword] = useState('')
6464

65-
const [ login, result ] = useMutation(LOGIN, { // highlight-line
65+
const [ login ] = useMutation(LOGIN, { // highlight-line
6666
onError: (error) => {
6767
setError(error.graphQLErrors[0].message)
6868
}
6969
})
7070

71-
// highlight-start
72-
useEffect(() => {
73-
if ( result.data ) {
71+
const submit = async (event) => {
72+
event.preventDefault()
73+
//highlight-start
74+
const result = await login({ variables: { username, password } })
75+
if (result.data) {
7476
const token = result.data.login.value
7577
setToken(token)
7678
localStorage.setItem('phonenumbers-user-token', token)
7779
}
78-
}, [result.data])
79-
// highlight-end
80-
81-
const submit = async (event) => {
82-
event.preventDefault()
83-
84-
login({ variables: { username, password } })
80+
//highlight-end
8581
}
8682

8783
return (
@@ -109,9 +105,6 @@ const LoginForm = ({ setError, setToken }) => {
109105
export default LoginForm
110106
```
111107

112-
We are using an effect hook to save the token's value to the state of the *App* component and the local storage after the server has responded to the mutation.
113-
Use of the effect hook is necessary to avoid an endless rendering loop.
114-
115108
Let's also add a button which enables a logged-in user to log out. The button's onClick handler sets the *token* state to null, removes the token from local storage and resets the cache of the Apollo client. The last step is [important](https://www.apollographql.com/docs/react/networking/authentication/#reset-store-on-logout), because some queries might have fetched data to cache, which only logged-in users should have access to.
116109

117110
We can reset the cache using the [resetStore](https://www.apollographql.com/docs/react/api/core/ApolloClient#resetstore) method of an Apollo *client* object.

0 commit comments

Comments
 (0)