[React] need help with redirect for unauthenticated users

I’m using following method for redirect in my authenticated component this.$f7.views.main.router.navigate('/'); And I’ve also tried this.$f7router.navigate('/') method. But none of these method is working.

react : 16.13.0
framework7 : 5.7.10
framework7-react : 5.7.10

Authenticated component.

import React, { Component } from 'react';
import { Page, Row, Col } from 'framework7-react';

class Authenticated extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    return this.redirect();
  }
  componentDidUpdate() {
    return this.redirect();
  }
  redirect = () => {
    const { loggingIn, userId } = this.props.f7router.params;
    console.log(loggingIn);
    if(!loggingIn) {
      console.log('redirect!');
      this.$f7.views.main.router.navigate('/');
    } else {
      console.log('no redirect');
    }

  }
  render() {

    const { Component, ...rest } = this.props;
    return (
      <Page>
      <Component { ...rest } />
      </Page>
    )
  }
}


export default Authenticated;

When I change the route, in console I can see the outputs “redirect!”. But navigate function doesn’t have any effect!

It won’t work because current page loading is in progress. It should be done on routes level, for example, using route’s beforeEnter https://framework7.io/docs/routes.html#route-before-enter-leave

Thank you for the response.

I’m using the following the beforeEnter function now.
Not sure whether if I’m using resolve incorrectly or it is an expected behaviour.

I’m not able to redirect user if they are not logged in.

I’m using resolve as follows.

if (loggedIn) {
    resolve();
} else {
   resolve({url: '/login'}); // not working!
   resolve({component: 'LoginPage'}); // not working!
}

Thank you.

Logic should be the following:

beforeEnter(to, from, resolve, reject) {
  const router = his;
  if (loggedIn) {
    resolve();
  } else {
    reject();
    router.navigate('/login');
  }
}

2 Likes

Thank you. @nolimits4web

This worked for me.

function checkAuth (to, from, resolve, reject) {
  let loggedIn = isUserLoggedIn();
  if (loggedIn) {
    resolve();
  } else {
    reject();
    this.navigate('/login');
  }
}

this.navigate(’/topage’); is not working for me, any advise what i am missing on the code

image

here’s my alternate solution, would this be okay? the routes would depend on the rules on the users