I have an issue on ReactJS about an infinite loop of an Axios request link to a componentDidMount function.
Here the thing :
- First : user receive a link by email (with a token in parameter)
- Second : When they clicked on the link, they arrived on a webpage where they can reset their password. I need to check if the token is always available : depending of that, the render will be different.
To check the token, I made a POST request via a componentDidMount.
Finally, I get the right render BUT my request is call again and again, creating an infinite loop on my server. It seems that my child component is re-construct again and again.
Here's my code :
Child component :
import React from 'react';
import {Container} from 'reactstrap';
export default class ResetPassword extends React.Component {
constructor(props) {
super(props);
console.log('CONSTRUCT')
}
componentDidMount() {
if (this.props.appState.loading ≡ false) {
console.log('componentDidMount')
let url = window.location.pathname;
let verifToken = url.substr(15);
this.props.checkToken(verifToken); //Make axios call on App.js
}
}
render() {
const {expiredToken} = this.props.appState;
console.log(expiredToken)
return (
<div className="ResetPassword">
<Container>
{expiredToken === true ?
(<div>VOTRE TOKEN A EXPIRE</div>
) : (<div>CHANGER MON MOT DE PASSE</div>)}
</Container>
</div>
)
}
}
Parent Component :
import axios from 'axios';
import ResetPassword from "./components/SignUp/ResetPwd";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
expiredToken : null
};
this.checkToken = this.checkToken.bind(this);
}
checkToken(token) {
console.log('checkToken');
this.setState({loading: true}, () => {
let url = `${this.state.config.apiURL}/checkToken`;
let method = 'post';
axios.request({
url: url,
method: method,
data: {
token: token
}
}).then(results => {
if (results.data === null) {
this.setState({
loading: false,
expiredToken: true
})
} else {
console.log(results.data);
this.setState({
loading: false,
expiredToken: false
});
}
})
})
}
render() {
const ResetPwd = (props) => {
return (
<div>
<ResetPassword appState={this.state} {...props} checkToken={this.checkToken}/>
</div>
)
};
}
}
And in my console DevTool, I have my 5 console.log() which turn into an infinite loop :
- CONSTRUCT --> console.log() from constructor in child
- expiredToken --> console.log() from render in child
- ComponentDidMount → console.log() from componentDidMount
- verifToken → console.log() from componentDidMount
- checkToken --> console.log() from parent