Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs var not defined inside a condition

I've a strange problem, I modified a working function from this:

    const reqBody = { bio: this.state.infoContent };    

    const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
        axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
            .then((result) => {
                //...
            })
            .catch((err) => {
               //...
            })

to this:

    // the condition is the difference
    if ( type == 'bio' ){
        const reqBody = { bio: this.state.infoContent };    
    }else{
        const reqBody = { bio: this.state.infoContent };
    }

    const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
        axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
            .then((result) => {
                //...
            })
            .catch((err) => {
               //...
            })

Now happen a strange thing, in the first version the code working properly, in the second, the condition in reqBody cause this error:

'reqBody' is not defined no-undef

Now, it's possible that the axios code is executed before the condition? Ok that the js is async but seems really strange this behaviour, someone can help me to understand why this happen?

like image 894
red Avatar asked Mar 18 '26 04:03

red


1 Answers

It's because you defined the reqBody variable inside the if-else block. It would not be available outside that scope. You need to define it in a common-scope so that other logic within your function has access to it.

let reqBody;

if ( type == 'bio' ){
    reqBody = { bio: this.state.infoContent };    
}else{
    reqBody = { bio: this.state.infoContent };
}

const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
    axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
        .then((result) => {
            //...
        })
        .catch((err) => {
           //...
        })
like image 65
Chris Ngo Avatar answered Mar 19 '26 17:03

Chris Ngo