Ustawianie zmiennej przed renderem

0

Hej, jestem początkujący w react. Zrobiłem sobie backend od strony springa i wszystko śmiga. Tak samo logowanie i wylogowywanie od strony reacta itd.

Chciałbym aby dostęp do strony miały tylko osoby z określonym uprawnieniem i zalogowane. Wszystko niby zrobiłem, ale niestety żeby przejść do strony muszę kliknąć 2 razy link, gdyż zanim zmienię zmienną czy uzytkownik jest autoryzowany to już wykonuje się render.

Prosiłbym o pomoc jak najpierw odwołać się do backendu, ustawić zmienną i dopiero wykonać render. Takie coś nie działa

class RegisterComponent extends Component {

    //Tutaj sprawdzam czy użytkownik jest zautoryzowany aby wyświetlić ten komponent
    componentDidMount() {
         this.checkAuthorizationStatus();
        // Auto initialize all the things!
        M.AutoInit();
    }

    //Sprawdzam czy jest zautoryzowany i jaką ma role
    checkAuthorizationStatus(){
        axios.get(API_URL+`/logged_in`)
            .then(response=>{
               if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
                   this.state.authorized = true;
               }
               else{
                   this.state.authorized=false;
               }
            })
    }



    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: '',
            role : 'ROLE_ADMIN',
            hasCreationFailed: false,
            showSuccessMessage: false,
            authorized : false
        }
    }

    handleChange = (event) => {
        this.setState(
            {
                [event.target.name]: event.target.value
            }
        )
    }

    submitClicked = () => {
        console.log({login: this.state.username,
            password: this.state.password,
            roles: [{"role":this.state.role}]})
        axios.post(API_URL + '/admin/register', {
            login: this.state.username,
            password: this.state.password,
            roles: [{"role":this.state.role}]
        })
            .then((response) => {
                this.setState({
                        showSuccessMessage: true,
                        hasCreationFailed: false
                    }
                )
                console.log(response)
            })
            .catch((error) => {
                this.setState({
                    showSuccessMessage: false,
                    hasCreationFailed: true
                })
                console.log(error)
            })
    }





    render() {

        if(this.state.authorized===true){
            return (
            <div className="row container">
                <div className="col s10 offset-s1 l4 offset-l4">
                    <div className="purple-text accent-2"><h5>Create New Account</h5></div>
                    <div className="input-field">
                        <select value={this.state.role} onChange={this.handleChange} name="role">
                            <option value='ROLE_ADMIN'>Administrator</option>
                            <option value='ROLE_TABLE'>Klient</option>
                            <option value='ROLE_WORKER'>Pracownik</option>
                        </select>
                    </div>
                    <div className="input-field">
                        <input className="validate" type="text" id="username" name="username"
                               value={this.state.username} onChange={this.handleChange}/>
                        <label htmlFor="username">Username</label>
                    </div>
                    <div className="input-field">
                        <label htmlFor="password">Password</label>
                        <input type="password" id="password" name="password" value={this.state.password}
                               onChange={this.handleChange}/>
                    </div>

                    <button className="btn blue col l12 waves-effect waves-light"
                            onClick={this.submitClicked}>Zarejestruj użytkownika
                    </button>
                    {this.state.showSuccessMessage &&
                    <div className="green-text">Rejestracja zakończona powodzeniem</div>}
                    {this.state.hasCreationFailed && <div className="red-text">Rejestracja nie powiodła się</div>}
                </div>
            </div>
        )
    }else return (<></>)
    }
}

export default RegisterComponent

Próbowałem jeszcze tego, ale tutaj znowu nie ustawia tej zmiennej przed ifem nie wiem czemu...

class AuthenticatedRoute extends Component {

    constructor(props) {
        super(props)

        this.state = {
            authorized: false
        }
    }

    checkAuthorizationStatus(){
        axios.get(API_URL+`/logged_in`)
            .then(response=>{
                if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
                    this.state.authorized = true;
                }
                else{
                    this.state.authorized=false;
                }
            })
    }



    render() {
        this.checkAuthorizationStatus();
        console.log(this.state.authorized)
        if (this.state.authorized===true) {
            return <Route {...this.props} />
        } else {
            return <Redirect to="/login" />
        }

    }
}
export default AuthenticatedRoute
0

Zrobiłem coś takiego i wszystko działa ALE nie wyświetla mi się lista do wybrania roli, nie mam pojęcia czemu....


import React, {Component} from 'react'
import axios from 'axios';
import M from "materialize-css";
import {API_URL} from "../ApiUrl";
import { Route, Redirect } from 'react-router-dom'

class RegisterComponent extends Component {

    //Tutaj sprawdzam czy użytkownik jest zautoryzowany aby wyświetlić ten komponent
    componentDidMount() {

        this.checkAuthorizationStatus();
        M.AutoInit();

        // Auto initialize all the things!
    }

    //Sprawdzam czy jest zautoryzowany i jaką ma role
    checkAuthorizationStatus(){
        axios.get(API_URL+`/logged_in`)
            .then(response=>{
               if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
                   this.setState({authorized:true})
                   console.log("W then")
                   //this.forceUpdate();

               }
               else{
                   console.log("W else")
                   return <Redirect to="/login" />
               }
            })
    }



    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: '',
            role : 'ROLE_ADMIN',
            hasCreationFailed: false,
            showSuccessMessage: false,
            authorized : false,
        }
    }

    handleChange = (event) => {
        this.setState(
            {
                [event.target.name]: event.target.value

            }
        )
    }

    submitClicked = () => {
        console.log({login: this.state.username,
            password: this.state.password,
            roles: [{"role":this.state.role}]})
        axios.post(API_URL + '/admin/register', {
            login: this.state.username,
            password: this.state.password,
            roles: [{"role":this.state.role}]
        })
            .then((response) => {
                this.setState({
                        showSuccessMessage: true,
                        hasCreationFailed: false
                    }
                )
                console.log(response)
            })
            .catch((error) => {
                this.setState({
                    showSuccessMessage: false,
                    hasCreationFailed: true
                })
                console.log(error)
            })
    }





    render() {

        const{authorized} = this.state
            return (
                <React.Fragment>
                {authorized ?(
                <div className="row container">
                    <div className="col s10 offset-s1 l4 offset-l4">
                        <div className="purple-text accent-2"><h5>Create New Account</h5></div>

                        <div className="input-field">
                            <select value={this.state.role} onChange={this.handleChange} name="role">
                                <option value='ROLE_ADMIN'>Administrator</option>
                                <option value='ROLE_TABLE'>Klient</option>
                                <option value='ROLE_WORKER'>Pracownik</option>
                            </select>
                        </div>

                        <div className="input-field">
                            <input className="validate" type="text" id="username" name="username"
                                   value={this.state.username} onChange={this.handleChange}/>
                            <label htmlFor="username">Username</label>
                        </div>
                        <div className="input-field">
                            <label htmlFor="password">Password</label>
                            <input type="password" id="password" name="password" value={this.state.password}
                                   onChange={this.handleChange}/>
                        </div>


                        <button className="btn blue col l12 waves-effect waves-light"
                                onClick={this.submitClicked}>Zarejestruj użytkownika
                        </button>
                        {this.state.showSuccessMessage &&
                        <div className="green-text">Rejestracja zakończona powodzeniem</div>}
                        {this.state.hasCreationFailed && <div className="red-text">Rejestracja nie powiodła się</div>}
                    </div>
                </div>

            ):(<></>)}

                    </React.Fragment>

)}

}

export default RegisterComponent

1 użytkowników online, w tym zalogowanych: 0, gości: 1