简体   繁体   中英

I want to setState before doing axios http request, but can't

So, i want to change my props state before i send those to my backend through http request, but axios send those state before my if statement code execute. I don't understnad with this async thing. Here's the code

 login(){ const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource'; this.setState(()=>{ if (this.state.email.indexOf('@') == -1){ return {email: ''} } else { return {username: ''} } }) axios.post(url, this.state).then(response => { if (response.data["message"]) this.setState({message: response.data["message"]}) else this.setState({message: response.data["token"]}) }) }

is someone has any solution?

You can do it this way. First the state is set, then the axios request is being done. The setState function has as second parameter a callback.

Have a look also into the react documentation: https://reactjs.org/docs/react-component.html#setstate

login(){
    const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource';
    this.setState(()=>{
        if (this.state.email.indexOf('@') == -1){
            return {email: ''}
        } 
        else {
            return {username: ''}
        }
    },() => {
        axios.post(url, this.state).then(response => {
        if (response.data["message"])
            this.setState({message: response.data["message"]})
        else
            this.setState({message: response.data["token"]})
        })
    });
}

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