By the time the component is rendered, it seems componentDidMount
has been called twice already and because the account has been verified already, different data is received from the server.
My problem is that I need my API Key to start a session and have different options coming from the server defined as booleans within an object for conditional rendering. The API key is received for only one of those options which is when I have just verified an account.
componentDidMount
is called twice so the first time, I receive the API key, but not the second time.
I tried using a conditional inside componentDidMount so the API call would be made once but state is emptied after the first time so it still gets called twice.
class Verify extends Component {
state = {
APIkey: '',
token: '',
userHasJustBeenActivated: false,
newTokenCreated: false,
userDeleted: false,
userAlreadyActivated: false,
errorMessage: '',
dataWasFetched: false,
}
componentDidMount = () => {
console.log('this.state.dataWasFetched :', this.state.dataWasFetched)
if (this.state.dataWasFetched) {
return
} else {
console.log('location :', this.props.location)
axios
.get(`/api/auth/verify${this.props.location.search}`)
.then(res => {
console.log(JSON.stringify(res.data))
const {
APIkey,
userHasJustBeenActivated,
newTokenCreated,
userDeleted,
userAlreadyActivated,
} = res.data
this.setState({
APIkey: APIkey,
userHasJustBeenActivated: userHasJustBeenActivated,
newTokenCreated: newTokenCreated,
userDeleted: userDeleted,
userAlreadyActivated: userAlreadyActivated,
dataWasFetched: true,
}, () => {
if (APIkey) {
cookies.setCookie('session', APIkey)
console.log('this.state :', this.state)
this.props.update()
}
})
})
.catch(err => {
const { data } = err.response
this.setState({
errorMessage: data,
})
})
}
}
I tried adding a conditional with dataWasFetched so that the call to the API would only be made once but it seems that state is being emptied with each new call.
When I check the console the value for state.dataWasFetched
is false and this.state
is not logged on the second call.