0

I need to call different function based on event and condition.

Let me explain on this example:

export class MyComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isLoggedIn: true,
        };

        this.login = () => {
            this.setState({isLoggedIn: true})
        };

        this.logout = () => {
            this.setState({isLoggedIn: false})
        };

        this.handleLogin = () => {
        };
    }

    componentDidMount() {
        const {store} = this.props;

        store.on('isLoggedIn').subscribe(isLoggedIn => {
            this.handleLogin = isLoggedIn ? this.logout : this.login;
        });
    }

    render() {
        const {isLoggedIn} = this.state;
        
        return (
            <NavLink to={{pathname: `${prefix}login`, isLoggedIn}}>
                <div role="presentation" onClick={this.handleLogin}>isLoggedIn ? 'Logout' : 'Login'}</div>
            </NavLink>
        );
    }
}

based on isLoggedIn eventlistener i need to set proper onClick reference. So i will change the state and sent via Navlink. Then i can listen to ComponentDidUpdate in redirected component.

redirected component lifecycle method:

ComponentDidUpdate({location}, prevState) {
    {isLoggedIn: isLoggedInPrev} = location;
    {isLoggedIn} = this.props;
    if(isLoggedIn !== isLoggedIn) {
        // do something
    }
}

Do anybody knows the trick?

EDIT - i did some "workaround" :

...
this.handleLogin = doLogin => {
            if (doLogin) {
                this.login();
            } else {
                this.logout();
            }
        };
    }

    componentDidMount() {
        const {store} = this.props;
        if (store.get('isLoggedIn')) this.setUserFromJwt();

        store.on('isLoggedIn').subscribe(isLoggedIn => {
            this.setState({doLogin: !isLoggedIn});
        });
    }
...

in render

<NavLink to={{pathname: `${prefix}login`, isLoggedIn}} activeClassName={ACTIVE_CLASS}>
   <div role="presentation" onClick={() => this.handleLogin(doLogin)}>{store.get('isLoggedIn') ? loggedInHeader : 'Login'}</div>
</NavLink>

now the state corresponds the action i need. But in Login componant no change in props. Both prevProps.location and this.props.location are unchanged.

Martin Fric
  • 726
  • 2
  • 9
  • 27
  • Instead of keeping loggedIn at component level you can keep it at redux level and then use that property to decide the route while navigation. That would be the correct way of doing conditional navigation. – Mohit Jul 02 '20 at 13:31
  • ok. But how will i let Login component know, when should he trigger redirect to login or logout? i need to bind it to clickevent – Martin Fric Jul 02 '20 at 13:46
  • Then I guess you don't need to inform login component. This decision will be taken at that level only where routing decisions are made. – Mohit Jul 02 '20 at 15:16

0 Answers0