Extracting a value from Two API calls in ReactJS - reactjs

How will I get the value from the first API call and use it in the second API call?
var custAcctNum = QueryString.getValue("customer");
ProxyData.getData('/customer/api/customers/' + custAcctNum, (data) => {
this.setState({ dataCust: dataCust });
});
var deviceId =  dataCust.ioTDeviceId;
ProxyData.getData('device/api/devices/' + deviceId, (data) => {
this.setState({ data: data });
});

You can do something like below. Calling the second async function in the callback of first function.
var custAcctNum = QueryString.getValue("customer");
ProxyData.getData('/customer/api/customers/' + custAcctNum, (data) => {
this.setState({ dataCust: dataCust });
var deviceId = dataCust.ioTDeviceId;
ProxyData.getData('device/api/devices/' + deviceId, (data) => {
this.setState({ data: data });
});
});

Related

How to store http angularjs call response to variable

I'm making http get call from angularJS function. Call works perfectly and get the response back but I need to store response in a variable so I can use it outside of $http. I tried to keep in $scope.data.submissionFileID but alert($scope.data.submissionFileID) says undefined. Also I want me make this call synchronous. I'm new to this, can you please help to modify this below code?
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.data.submissionFileID = response; // response is an integer such as 123
});
alert($scope.data.submissionFileID); // This is undefined, what should I do to fix it?
var content = "<h7><b>" + "Created at </b>" + $scope.data.submissionFileID + "</h7><br><br>";
}
Something to consider is that the alert(...) is being called before the async function has a chance to complete. An option would be to send the response off to another function that sets the $scope variable and does whatever else you might want.
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.doTheThing(response);
});
}
$scope.data = {}
$scope.doTheThing = function(response) {
$scope.data.submissionFileID = response;
}
in the HTML template file...
<div ng-if="!data.submissionFileID">Retrieving Data....</div>
<div ng-if="data.submissionFileID">
<h7><b>Created at </b> {{data.submissionFileID}}</h7>
</div>

Angular ng-table loading from server with pagination

I am trying to figure out how to populate an ng-table and apply the total value for the params. It appears there are examples that are showing almost what I'm doing - but not exactly and the total never gets set.
$scope.tableParams = new NgTableParams({page: 1, count: 25},
{
counts: [],
getData: function(params)
if (CompaniesView.ViewInitialized)
return CompaniesView.RetrieveCompanies($scope, $http, function ()
{
params.total($scope.RequestFilter.TotalCompanies);
return $scope.TableParams.data;
});
}
});
My RetrieveCompanies function retrieves he data - and will call a callback function on completion. I was under the impression at this point I could set the params.total, but is not working. I see that examples are doing similar, except they are performing a jQuery API operation directly. I am not sure why this does not work. I would have thought anytime setting the total would cause the table pagination controls to update - but it appears it has to be done within the detData call. But if you are making an async call how can we have the total set in the call since it won't have data until the async completes - which means the
getData call has already finished.
Probably missing some concept here -- but I am not an expert when it comes to jQuery or angular.
Peter
Update:
RetrieveCompanies function
RetrieveCompanies: function (scope, http,callback)
{
scope.IsLoading = true;
var Data =
{
AuthoirzationType: TokenRetrieval.SessionAuth,
SessionId: activeSession
};
var tokenRequest =
{
params: Data
};
performVeilabilityTokenRetrieval(http, tokenRequest,
function (response)
{
if (true)
{
if (!response.HasError)
{
scope.RequestFilter.State = scope.selectedState.Value
scope.RequestFilter.regionsearch = scope.selectedRegion.id;
scope.RequestFilter.checkadminStaff = scope.selectedAdmin.value;
//tableParams
scope.RequestFilter.Page = scope.tableParams.page();
scope.RequestFilter.PageCount = scope.tableParams.count();
var config =
{
headers:
{
Authorization: 'Bearer ' + response.RequestToken
},
params: scope.RequestFilter
}
http.get(CompaniesView.Companies_api_urls.loadCompaniesRequest, config)
.then(
function (response)
{
scope.RequestFilter.TotalCompanies = response.data.companieslistTotal;
scope.TableParams.data = response.data.companies;
if (callback != null) callback();
},
function (data, status, headers, config) //error
{
scope.IsLoading = false;
}
);
}
else
{
scope.request.requestToken = null;
//CreateExpenseView.PrepareRESTResults(data.RestResults);
}
}
else
{
scope.request.requestToken = null;
scope.request.error = data.replace(/\"/g, "");
}
});
}
Ok; finally found what was wrong. The ng-table getData operation requires a promise to be returned. My function was not configured as a deferred promise and once I realized this I put in place the required modification for my data retrieval to return a promise. One big point -- when I wrapped my call with a when - I completed with a done - and getData is operating off a then (from the promise). Once those changes were in place the pagination (total) operation worked.
Peter

Using $resource in AngularJS and getting an undefined response

I have the following code:
vm.getTheSector = function () {
SectorDataFactory.get({action:'getSector', sectorName:vm.selected}, function (response) {
vm.industry.sector = response.theSector;
});
vm.saveTheIndustry()
};
vm.saveTheIndustry = function () {
SectorDataFactory.save({action: 'saveIndustry'}, vm.industry, function (response) {
vm.responseMessage = response.theMessage;
});
};
I am getting a sector object from a RESTful web service however vm.industry.sector is undefined. I'm trying to then POST the industry object however the sector is null.
vm.getTheSector = function () {
SectorDataFactory.get({action: 'getSector', sectorName: vm.selected}, function (response) {
vm.industry.sector = response.theSector;
vm.saveTheIndustry()
});
};
Thanks to mbeso. The vm.saveTheIndustry() now executes as part of the success callback.

React/React Native: Execution order in a Component

I am not able to figure out the sequence of code execution in react native. The following code logs test, test 2 and then test 1. I want to change value of submittedURI.
constructor(props) {
super(props);
this.state = {
enterURI: ''
};
}
onUriTextChanged(event) {
this.setState({ enterURI: event.nativeEvent.text });
}
onSubmitPress() {
var submittedURI = this.state.enterURI;
console.log("test "+submittedURI);
var url = encodeURIComponent(submittedURI), data = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.urlmeta.org/?url=" + url);
xhr.send(data);
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
// console.log(this.responseText);
var responseJSON = JSON.parse(this.responseText);
submittedURI = responseJSON.meta.image;
console.log("test 1 "+submittedURI);
}
});
this.props.onURISubmit(submittedURI);
console.log("test 2 "+submittedURI);
}
The function in the xhr.addEventListner("readystatechange", function() { ... }) is a callback and get's called after the request is DONE. Therefore console.log("test 2 "+submittedURI); is called before the request is completed.
See the docs here (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange)
If you want to change submittedURI you are going to have to call this.props.onURISubmit(submittedURI); function within the readystatechange callback. Make sure the callback has the proper context to access this.props.

Promises - I get the same result after $q.all

I have this code:
return WordPress.getAllCategories()
.then(function (cats) {
var category = {};
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
To load latest articles from each category for a magazine main page (using WordPress REST api with $http requests). The process is as follow:
1. Load all categories.
2. Get latest post from each category.
3. Get the media of the latest post.
4. Build the category.post object based on the post data and add the thumbnail from the media received (post-specific).
5. After all promises are resolved, $scope.categories = categories to apply for view.
The problem:
With the code above, I can see the console logs search for different posts and medias properly, but at the end I get an array containing the categories, all posts are the same. Same title, content, thumbnail image and everything.
What am I doing wrong with the promises here?
P.S. All WordPresss service functions work properly. They return a resolved promise after receiving the necessary data via $http requests from the WordPress blog.
Regards.
Try this way:
return WordPress.getAllCategories()
.then(function (cats) {
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
var category = {}; // moved declaration here to return new instance each time
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
You were returning same category object instance, I just create new instance every time inside getMediaById callback

Resources