React is complaining about code below, saying it useEffect is being called conditionally:
JavaScript
x
35
35
1
import React, { useEffect, useState } from 'react'
2
import VerifiedUserOutlined from '@material-ui/icons/VerifiedUserOutlined'
3
import withStyles from '@material-ui/core/styles/withStyles'
4
import firebase from '../firebase'
5
import { withRouter } from 'react-router-dom'
6
7
function Dashboard(props) {
8
const { classes } = props
9
10
const [quote, setQuote] = useState('')
11
12
if(!firebase.getCurrentUsername()) {
13
// not logged in
14
alert('Please login first')
15
props.history.replace('/login')
16
return null
17
}
18
19
useEffect(() => {
20
firebase.getCurrentUserQuote().then(setQuote)
21
})
22
23
return (
24
<main>
25
// some code here
26
</main>
27
)
28
29
async function logout() {
30
await firebase.logout()
31
props.history.push('/')
32
}
33
}
34
35
export default withRouter(withStyles(styles)(Dashboard))
And that returns me the error:
React Hook “useEffect” is called conditionally. React Hooks must be called in the exact same order in every component render.
Does anyone happen to know what the problem here is?
Advertisement
Answer
Your code, after an if
statement that contains return
, is equivalent to an else
branch:
JavaScript
1
8
1
if(!firebase.getCurrentUsername()) {
2
3
return null
4
} else {
5
useEffect( )
6
7
}
8
Which means that it’s executed conditionally (only when the return
is NOT executed).
To fix:
JavaScript
1
11
11
1
useEffect(() => {
2
if(firebase.getCurrentUsername()) {
3
firebase.getCurrentUserQuote().then(setQuote)
4
}
5
}, [firebase.getCurrentUsername(), firebase.getCurrentUserQuote()])
6
7
if(!firebase.getCurrentUsername()) {
8
9
return null
10
}
11