I am currently building slack clone. I want to check whether the user is already logged in whenever the component mounts, first, if he is then push it home page else to the login page. I use react hooks to check instead of componentDidMount
and also redux to store the login state of the user using mapDispatchToProps
.
I am getting the warning
import React,{useEffect} from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import Login from './components/Auth/login'
import Register from './components/Auth/register'
import reportWebVitals from './reportWebVitals';
import {BrowserRouter as Router,Switch,Route,useHistory,withRouter} from 'react-router-dom'
import 'semantic-ui-css/semantic.min.css'
import firebase from './firebase'
import { createStore } from 'redux'
import { Provider,connect} from 'react-redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from './reducers/index';
import * as actions from './actions/index';
import Spinner from './spinner'
const store=createStore(rootReducer,composeWithDevTools())
const Root=(props)=>{
const history=useHistory()
useEffect(() => {
console.log("1")
firebase.auth().onAuthStateChanged(user=>{
if(user){
props.setUser(user);
history.push('/home')
}
else{
history.push('/login')
props.clearUser();
}
})
},[history.location.hash,history])
return props.isLoading ? <Spinner/>:(
<Switch>
<Route exact path="/home" component={App} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</Switch>
)
}
const mapStateToProps=state=>{
return {
isLoading:state.user.isLoading,
user:state.user.currentuser
}}
const mapDispatchToProps=dispatch=>{
return{
setUser:(user)=>dispatch(actions.SETuser(user)),
clearUser:()=>dispatch(actions.CLEARuser())
}
}
const RootwithAuth=withRouter(connect(mapStateToProps,mapDispatchToProps)(Root))
ReactDOM.render(
<Provider store={store}>
<Router>
<RootwithAuth/>
</Router>
</Provider>,
document.getElementById('root')
);
reportWebVitals();