0

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?

weshedrick
  • 99
  • 1
  • 1
  • 7
  • 2
    Is this the same component with your `Router` in it? If so, you'll need to have the router at a higher level to have access to its context. See this https://stackoverflow.com/questions/62614433/react-router-why-is-the-usehistory-undefined-in-react – Nick Feb 12 '21 at 01:06
  • 1
    you need to first setup a Router. The error just says that it didn't find that object in your current context. – windmaomao Feb 12 '21 at 01:08
  • Nick, I see it now! This helps me better understand what useHistory is in the first place. There is no 'history' yet because the Router elements are below. – weshedrick Feb 12 '21 at 01:20
  • If you don't want to move your router you can create your own history object earlier and pass it to your router. – Jacob Smit Feb 12 '21 at 01:56

0 Answers0