Objective: Check if valid session exists. If so, redirect user to dashboard.
The error occurs at history.push()
but I'll share the larger context below:
import {
BrowserRouter as Router,
Switch,
Route,
useHistory
} from 'react-router-dom';
import { useState, useEffect } from 'react'
import Sidebar from './components/Sidebar';
import Credentials from './components/Credentials';
import Dashboard from './components/Dashboard';
import Hero from './components/Hero';
import axios from 'axios';
function App() {
const [loggedIn, setLoggedIn] = useState(false);
const [id, setId] = useState(0)
const [name, setName] = useState('')
const [countOfJobs, setCountOfJobs] = useState(0)
const [appRatio, setAppRatio] = useState(0)
const [appReality, setAppReality] = useState(0)
const [inspiration, setInspiration] = useState({})
const [displayOutPut, changeDisplayOutput] = useState([]);
async function populateDashboard(uid){
console.log('populate dashboard is running')
const {data} = await axios.get(`/dashboard/dashboard-data/${uid}`)
console.log(data)
const { author, quote } = data.inspiration[0]
console.log('author', author)
changeDisplayOutput(data.jobsAppliedTo)
setCountOfJobs(data.jobCount)
setAppRatio(data.dailyAppGoal)
setAppReality(data.dailyAppReality)
setInspiration({author, quote})
}
const history = useHistory()
useEffect(()=> {
const checkSession = async () => {
const response = await axios.get('/sign-in/check-session')
if(response === 'null'){
return
} else {
populateDashboard(response)
console.log('popDash ran')
history.push('/dashboard')
}
}
checkSession()
}, [])
The error occurs at history.push('/dashboard)
: Cannot read property 'push' of undefined
Why am I not able to use history.push('/dashboard')
inside of useEffect? How can I redirect the user to dashboard otherwise?