The component I have added here gets rendered post login. All I needed is to redirect to login when the session has expired. My problem is mainly inside render. On successful login, the page gets redirected to Home and shows this.state.success.toString() as true and as false if the session has expired. Till this, is fine.
When I uncomment the lines I left commented, and comment out the last line, render function is to either show a message in Home or redirect to login.
But code doesn't work that way. It goes to the Home route and again gets redirected to Login. Even the componentDidUpdate() method didn't get called. I couldn't understand why. Could you please help to solve this?
import React from 'react';
import './App.css';
import axios from 'axios';
import { Redirect } from 'react-router-dom'
export default class Home extends React.Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
success: "",
message: "",
user: "",
cookies: ""
}
}
componentDidMount() {
this._isMounted = true;
axios.get('http://localhost:8080/auth/login/success', { withCredentials: true }).then((res) => {
console.log(res);
let data = res.data;
if (this._isMounted) {
this.setState({
success: data.success,
message: data.message,
user: data.user ? data.user : "",
cookies: data.cookies ? data.cookies : ""
})
}
}).catch((err) => {
let data = err.response.data;
if (this._isMounted)
this.setState({
success: data.success,
message: data.message,
user: data.user ? data.user : "",
cookies: data.cookies ? data.cookies : ""
});
})
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
// if (this.state.success)
// return <h1>{this.state.message}</h1>
// else {
// return <Redirect to="/login"></Redirect>
// }
return <h1>{this.state.success.toString()}</h1>
}
componentDidUpdate(previousProps, previousState) {
console.log(this.state);
}
}
componentDidMountrather thanrender