Yassine BHS Yassine BHS - 18 days ago 7
React JSX Question

Return variable with React method

I have this function in JS:

export let findUser = (user, pass) => fetch(baseURL+'/api/Login',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username:user,
password:pass,
})
})
.then((response) => response.json())
.then((res) => {
if(res.success === true){
return 'A';
}else{
alert(res.message);

}
}).
.done();


But when I call it in React like this :

var user = file.findUser(this.state.username,this.state.password);


I got undefined as content of variable user, How can I pass a value from the first function and get it in react native ?

Answer

I would suggest exporting the initial method call and handling the .then() and .done() within the area being exported to. For example:

I have this function in JS:

export let findUser = (user, pass) => fetch(baseURL+'/api/Login',{
    method: 'POST',
        headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username:user,
            password:pass,
        })
})

using in another file

let user // assign user within response block
file.findUser(this.state.username, this.state.password)
    .then((res) => { /* do what you want */ })
    .then((res) => { /* do what you want */ })
    .done()