Tanmoy Basak
Tanmoy Basak

Reputation: 142

Creating private route when isAuth comes from a callback

I am using react router private routing system. I'm checking authentication, by getting jwt from localstorage and cross checking against server in an axios promise.

However the private routing does not seem to wait for callback to return. Am i doing the authentication wrong? or is there a way of fixing this?

my axios promise to check auth.

const checkAuth = (cb) => {
    let token = localStorage.getItem("jwtToken");
    // console.log(token);
    if (token) {
        axios.defaults.headers.common["Authorization"] = token;
        axios
            .get("api/admin/auth/profile")
            .then(res => {
                localStorage.setItem("admin", res.data.admin);
                cb(null, res.data);
            })
            .catch(err => {
                showErr(err, cb);
            });
    } else {
        cb("Not authenticated", null);
    }
}

Private route set up.

const PrivateRoute = ({ component: Component, ...rest, checkAuth }) => 
(
    <Route {...rest} render={(props) => (
        checkAuth((isAuthenticated) => (
            isAuthenticated === true
            ? <Component {...props} />
            : <Redirect to={{
              pathname: '/login',
              state: { from: props.location }
            }} />
        ))
    )} />
)

Upvotes: 1

Views: 600

Answers (1)

lipp
lipp

Reputation: 5926

The checkAuth method returns nothing. A render function should return a component. I'd suggest to create a stateful CheckAuth component like this.

class CheckAuth extends React.Component {
  state = {}

  componentDidMount () {
    this.props.checkAuth(isAuthenticated => {
      this.setState({isAuthenticated})
    })
  }

  render () {
     return this.props.children({loading, isAuthenticated})
  }
}

const PrivateRoute = ({ component: Component, ...rest, checkAuth }) => 
(
    <Route {...rest} render={(props) => 
      <CheckAuth {...props} checkAuth={checkAuth}>
       {({isAuthenticated}) => (
         isAuthenticated === true
         ? <Component {...props} />
         : <Redirect to={{
           pathname: '/login',
           state: { from: props.location }
        )}
      </CheckAuth>
    )}</Route>

} 

Upvotes: 1

Related Questions