hidjou/classsed-graphql-mern-apollo

TypeError: Object(...)(...) is undefined in AuthRoute

Closed this issue · 3 comments

AuthRoute.js
`
import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";

import { AuthContext } from "../context/auth";

function AuthRoute({ component: Component, ...rest }) {
const { user } = useContext({ AuthContext });

return (
<Route
{...rest}
render={(props) =>
user ? : <Component {...props} />
}
/>
);
}
export default AuthRoute;
`

Gets the following Error:

TypeError: Object(...)(...) is undefined

Hello @aindriu80 !

At line 7:
const { user } = useContext({ AuthContext });
Should be changed to:
const { user } = useContext(AuthContext); //delete the curly braces {}

And since you're working on the Auth Route , you should be redirecting any user that attempts to go to routes such as "/login" or "/register" to the home page.

That being said at line 13 you should change from:
user ? : <Component {...props} />
to:
user ? <Redirect to="/"/> : <Component {...props}/>

So, the AuthRoute.js should look like this:

import React, {useContext} from 'react'
import {Route,Redirect} from 'react-router-dom'

import {AuthContext} from './context/auth'

function AuthRoute({component: Component, ...rest}){
  const {user} = useContext(AuthContext);
  
  return (
    <Route 
      {...rest}
      render={props => 
        user ? <Redirect to="/"/> : <Component {...props}/>
      }/>
  )
}

export default AuthRoute

That worked a treat, thanks!!

Your welcome,@aindriu80!
You can mark the issue as closed 😁.