So I have a login page that directs users to a profile page in which an asynchronous request is made retrieving a user's id number initiated at the componentDidMount event. Once I get the results back, I setState on the id with the data retrieved.
import React, { Component } from 'react';
import {Navbar} from 'react-materialize';
import {Link, Redirect} from 'react-router-dom';
import helper from '../utils/helper';
import axios from 'axios';
import logo from '../logo.svg';
import '../App.css';
class Profile extends Component {
constructor(props){
super(props);
this.state = {id: null, loggedIn: true};
this.logOut = this.logOut.bind(this);
}
componentDidMount(){
axios.get('/profile').then((results) => {
if(!this._unmounted) {
this.setState({id: results.data})
}
})
}
logOut(event){
axios.post('/logout').then((results) => {
console.log(results);
})
this.setState({loggedIn: false});
}
render() {
if(!this.state.loggedIn){
return <Redirect to={{pathname: "/"}}/>
}
if(this.state.id == null){
return <Redirect to={{pathname: "/login"}} ref="MyRef" />
}
return (
<div>
<Navbar brand='WorldScoop 2.0' right>
<ul>
<li><Link to="#" onClick={this.logOut}>Logout</Link></li>
</ul>
</Navbar>
<h1>Profile Page</h1>
<h2>Welcome {this.state.id} </h2>
</div>
)
}
}
export default Profile;
I am trying to make it so that someone cannot just type the '/profile' path in the url and be taken to a profile page. To do this I tried conditional rendering based on whether an id was retrieved from proper login authentication.That is why if you notice
if(this.state.id == null){
return <Redirect to={{pathname: "/login"}} ref="MyRef" />
}
this will redirect users back to the login page if they do not supply an email and password. I have tried making sure my profile component mounts and unmounts after receiving the data, but I still keeping getting the error message: Can only update a mounted or mounting component. I am confused when the component 'unmounts' .