简体   繁体   中英

In react, what is the best way to perform an API call and redirect before Render()?

I mostly do backend, so my javascript isn't all that, but I'm having a problem in my admin panel I'm designing. Some parts of the site can only be accessed by certain users.

Each time the protected component should load, I send a request to my REST server, which returns back either 200 or a 403, the 200 response contains a key called redirect , which is False . So my thinking was to do the following:

...
import { Redirect } from 'react-router-dom';
import axios from 'axios';


class MyProtectedComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            authCalled: false,
            redirect: true,
        };
    }

    componentDidMount() {
        console.log("mounting...")
        axios.get('<https://url>',
        {headers: {"Authorization": localStorage.getItem("token")}})
        .then(res => {
            this.setState({
                redirect: res.data.data.redirect,
                authCalled: true,
            });
        })
    }

    render() {
        if (this.state.authCalled === false) {
           return (
               <div className="animated fadeIn">
               <Row>
               <Col>
               authenticating...
               </Col>
               </Row>
               </div>
           )
       }

       if (this.state.redirect === true) {
           return <Redirect to={{pathname: "/nonauthpage"}} />;
       }

   return ( ....... <main code> ..... )

Now if the server sends back the 200 for the user is allowed to access, the component loads, but if not, the page gets stuck in the <authenticating> phase and never Redirect s.

All of my javascript is self-taught, If what I'm doing is bad practice for performing this type of thing, please let me know how to properly do it, or show me why this is not working so I get it working.

You're using axios which means if the response is not 200 (or 2XX) the then will not be executed and instead you will need to chain execute a .catch like below:

componentDidMount() {
    console.log("mounting...")
    axios.get('<https://url>',
    {headers: {"Authorization": localStorage.getItem("token")}})
    .then(res => {
        this.setState({
            redirect: res.data.data.redirect,
            authCalled: true,
        });
    }).catch(error => {
        // You can do additional checks here like e.g. check if the response code is 403 or 401 
        this.setState({
             redirect: true,
             authCalled: true
        });
    })
}

You can customize your code as below to make it works

....
import { Redirect } from 'react-router-dom';
import axios from 'axios';


class MyProtectedComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            authCalled: false,
            redirect: true,
        };
    }

    componentDidMount() {
        console.log("mounting...")
        axios.get('<https://url>',
        {headers: {"Authorization": localStorage.getItem("token")}})
        .then(res => {
            this.setState({
                redirect: res.data.data.redirect,
                authCalled: true,
            });
        }).catch(err => {
            this.setState({
                redirect: true,
                authCalled: true,
            });
        })
    }

    render() {
        if (this.state.authCalled === true) {
            if (this.state.redirect === true) { 
                return <Redirect to={{pathname: "/nonauthpage"}} />;
            } else {
                  return ( ....... <main code> ..... ) 
            }
        }
        else {
            return (
                <div className="animated fadeIn">
                    <Row>
                        <Col>
                        authenticating...
                        </Col>
                    </Row>
                </div>
            )
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM