hidjou / classsed-graphql-mern-apollo

408 stars 255 forks source link

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

Closed aindriu80 closed 3 years ago

aindriu80 commented 4 years ago

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

mariusflorescu commented 4 years ago

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
aindriu80 commented 4 years ago

That worked a treat, thanks!!

mariusflorescu commented 4 years ago

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