Reputation: 647
I have a function with two fetch requests. The first fetch request returns an array of objects which contains ACCTNO. I'm trying to use the returned ACCTNO is a second request. However I'm not having any success. I'm also trying to refer to this.state.buildUrl, as I need buildUrl to render in a view but I get the error saying this.setState is not a function or undefined. How can I use the first fetch response in my second request?
componentDidMount() {
var url = 'http://10.0.2.2:8080/combined';
var result = fetch(url, {
method: 'get',
}).then(function(response) {
return response.json();
}).then(function(data) {
var ACCTNO = data[0].ACCOUNT;
var FormData = require('form-data');
var form = new FormData();
form.append('businessId', '123456');
form.append('login', 'SAFConnectUser');
form.append('password', '123445678');
form.append('billingAccountNumber', ACCTNO);
form.append('signOffURL', 'fd');
form.append('timeOutURL', 'fd');
fetch('https://collectpay-uat.princetonecom.com/otp/namevaluepair/submitSingleSignOn.do', {
method: 'POST',
body: form
}).then((response) => response.text()).then((res) => {
if (res.error) {
console.log(res.error)
}
console.log(res)
var fields = res.split('|');
var getUrl = fields[3];
var buildUrl = getUrl.slice(14)
// Getting error that setState is not a function?
this.setState({buildUrl})
console.log(buildUrl)
console.log(ACCTNO)
})
})
}
render() {
return (
<WebView
source={{uri: this.state.buildUrl}}
style={{marginTop: 20}}
/>
);
}
}
export default acidirect;
Upvotes: 0
Views: 188
Reputation: 4972
Change all your functions to fat arrow functions so they can refer to this
:
class acidirect {
componentDidMount() {
fetch('http://10.0.2.2:8080/combined', {
method: 'get',
})
.then(response => response.json())
.then(data => {
var ACCTNO = data[0].ACCOUNT;
var FormData = require('form-data');
var form = new FormData();
form.append('businessId', '123456');
form.append('login', 'SAFConnectUser');
form.append('password', '123445678');
form.append('billingAccountNumber', ACCTNO);
form.append('signOffURL', 'fd');
form.append('timeOutURL', 'fd');
fetch('https://collectpay-uat.princetonecom.com/otp/namevaluepair/submitSingleSignOn.do', {
method: 'POST',
body: form
})
.then(response => response.text())
.then(res => {
var fields = res.split('|');
var getUrl = fields[3];
var buildUrl = getUrl.slice(14);
this.setState({buildUrl});
});
});
}
render() {
return (
<WebView
source={{uri: this.state.buildUrl}}
style={{marginTop: 20}}
/>
);
}
}
export default acidirect;
Upvotes: 1
Reputation: 2771
you can set your response from first fetch in state as
fetch('/url',{credentials: 'same-origin'}).then(function(response) {
return response.json();
}).then(this.setSomeState);
Now set your state
setSomeState: function(response) {
this.setState({
array: response
});
},
Now you can get it anywhere using
this.state.array
Upvotes: 0