I might be making a silly mistake but I have this REST API output that i am consuming in UI through React and I am partially getting the output. When i console log, i get the output for ( testRows is data in AJAX - this.setState({testRows: data});) :
this.state.testRows.Type as 'Application Performance'
but when i do this.state.testRows.Names[0] to print first value i.e. desc2, i face an error. What is the correct way to display or print array values of JSON in react?
{
"Names": [
"desc2",
"desc3"
],
"Result": 0,
"Type": "Application Performance",
"dateTime": [
"2016-07-26 20:35:55",
"2016-07-26 20:35:55"
]
}
ReactJS :
var App = React.createClass({
getInitialState: function () {
return {
testRows: []
};
},
componentWillMount: function (event) {
$.ajax({
type: "GET",
crossDomain: true,
url: /details/3,
success: function(data) {
this.setState({testRows: data});
}.bind(this),
error:function(data) {
alert("Data sending failed");
}
});
},
render: function() {
console.log(this.state.testRows.Type); ~~ I get the output
console.log(this.state.testRows.Names[0]); ~~ Error
return (
);
}
});
var element = document.getElementById('content');
ReactDOM.render(React.createElement(App), element);
You are trying to console log the Names from your render method.
Render method gets called immediately after the component is mounted, which means that your ajax has not completed by that time and so your state does not have Names and hence when you try to access an undefined error is thrown.
But after your ajax is completed and state is set, and when render is called again the if clause satisfies and your code works as the names is now available.
Related
I am using Angular and have to populate a table and for this i need an array which has values by multiple calls to server.
I have following scenerio
Angular Controller:
var application={};
var data-[];
$scope.tableData=[];
Restangular.all("a").getList().then(function(arr1){
for(var i=0;i<arr1.length;i++)
{
application.app=arr1[i];
Restangular.one("b",arr1[i].id).get().then(function(obj1){
application.obj1=obj1;
});
Restangular.one("c",arr1[i].id).get().then(function(obj2){
application.obj2=obj2;
});
data.push(application);
application={};
if(i==arr1.length-1){
$scope.tableData=data;
}
}
});
Now the table in view shows row equal to length of arr1 and also shows the data in arr1 but the data by other Restangular calls are not attached with that array except last iteration.
OnlyiIn last iteration the array is fully made including arr1,obj1,obj2 other array indexes r missing obj1 n obj2.
This is because of async behaviour of Restangular response but cannot understand how to handle it.
Note:
(Expected result)
data[
{
app:{
app_id:1,
status:1
},
obj1:{
name:"user1",
gender:"male"
},
obj2:{
telephone:"63532367",
address:"abc"
}
},
{
app:{
app_id:2,
status:1
},
obj1:{
name:"user2",
gender:"female"
},
obj2:{
telephone:"63532367",
address:"xyz"
}
},{
app:{
app_id:3,
status:1
},
obj1:{
name:"user3",
gender:"female"
},
obj2:{
telephone:"63532367",
address:"xyz"
}
}
]
(Current Result)
data[
{
app:{
app_id:1,
status:1
}
},
{
app:{
app_id:2,
status:1
}
},
{
app:{
app_id:3,
status:1
},
obj1:{
name:"user3",
gender:"female"
},
obj2:{
}
}
]
Restangular is async (all the Restangular.one() is left before the callback you pass to .then). That's why Promises is used.
Even if it would be possible to make Restangular to be sync you shouldn't do that because this will block the browser until the data is requested which will be a bad user experience.
You should try to get into Promise as they were designed to look like sync code but behave async.
You can try something like this:
var a = Restangular.all("a").getList().then(function(arr1){
// Some modification of the backend data response
return modifiedData; // Now this should be passed to each of those Restanngular.one() methods sequentially
});
Above code will return the Promise that is returned by the .then call, which can be chained as following concept:
(new Promise(function( resolve, reject){
$timeout(function() {
resolve("some");
});
}))
.then(function(data) {
return data+' data';
})
.then(function(data) {
return new Promise(function(resolve, reject) {
$timeout(function() {
resolve(data+' !!!!!!');
});
});
})
.then(function(data) {
// this will have 'some data !!!!!!'
console.log(data);
});
In my service I making http get request as shown below:
.factory('InvoicesGeneralService', function ($http) {
return {
getAgreementsByCourierId: function (courierId) {
console.log("Courier in Services" + courierId);
return $http.get('/api/agreements/byCourierId', {params: {courierId: courierId}}).then(function (response) {
return response;
});
}
};
});
And in browser console I am seeing the following response :
[
{
"id":3,
"number":"AGR53786",
"ediNumber":"EDI7365",
"startDate":"2012-09-02",
"endDate":"2018-07-01",
"courier":{
"id":2,
"name":"FedEx",
"url":"www.fedex.com",
"isActive":true,
"isParcel":true
},
"client":{
"id":4,
"code":"KJGTR",
"name":"Hearty",
"isActive":true,
"engageDate":"2011-07-07",
"isSendRemittance":true,
"upsUserName":"Tkd",
"upsPassword":"kuu",
"isEligibleForTracking":true,
"isEligibleForAuditing":true,
"status":5
}
}
]
And in my controller I am assigning it to result List :
$scope.resultList = InvoicesGeneralService.getAgreementsByCourierId(selCourierId);
But my resultList is always appearing as Empty. Can any one help me, why it is happening?
When I am trying to display resultList as shown below, it always shows empty object, {}. It supposed to display the response json array from the service but it is showing empty object.
<pre class="code"> {{resultList | json}}</pre>
$http returns a promise. Anything consuming that data needs to handle it like a promise too.
InvoicesGeneralService.getAgreementsByCourierId(selCourierId).then(function(data) {
$scope.resultList = data;
});
Also, your factory's then function is not doing anything at the moment. You should return the response's data from it.
return $http.get('/api/agreements/byCourierId', {params: {courierId: courierId}}).then(function (response) {
return response.data;
});
Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};
I am trying to read JSON reply from server. You can find my code here.
https://github.com/ameyjah/feeder
In firefox firebug, I can see that server has returned JSON reply but when I store that into $scope.variable, I am not able to access that information.
Module code
var res
angular.module('myApp.services', ['ngResource'])
.factory('feedFetcher', ['$resource',
function($resource) {
var actions = {
'sites': {method:'GET', params: { action:"sites"} ,isArray:false},
'feeds': {method:'GET', params: { action:"sites"} ,isArray:false}
}
res = $resource('/api/:action', {}, actions);
return res
}
]);
Controller code
$scope.sites = feedFetcher.sites().sites;
console.log($scope.sites);
Reply seen in firebug:
{
"sites": [
{
"id": 0,
"title": "google"
},
{
"id": 1,
"title": "yahoo"
}
]
}
I think I have messed up the way I should define my factory but I am not able to identify. Any help would be helpful.
When you call sites() it returns an empty object and initiates an AJAX request, which will populate the "sites" property on that object. I think you should use it like this:
$scope.results = feedFetcher.sites();
console.log($scope.results.sites); // will be undefined as AJAX not complete
Then in your html you can use the results and they will be filled in when AJAX completes, or watch for it:
$scope.$watch('results.sites', function() {
// this will be called twice, once initially
// and again whenever it is changed, aka when AJAX completes
console.log($scope.results.sites);
};
I have a gridpanel , a Model, an autosync Store with an ajax proxy with read and update functions and a RowEditing plugin in extjs4 .
Consider the following json:
{ "success": true,"Message":"Grid Data Successfully updated.", "users": {"uname":"jdoe","fname":"John","lname":"Doe","SSN":125874,"mail":"jdoe#example.org"},{"uname":"jsmith","fname":"Jack","lname":"Smith","SSN":987456,"mail":"smith#example.com"}}
I want to know if there is a way to render the value of "Message" to an HTML div tag (my_div for example) after receiving each response?
You can use the DOM Helper, see the sencha api : http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomHelper
Ext.onReady(function(){
Ext.DomHelper.insertHtml('beforeBegin', Ext.getDom('test'), "Prepend this string");
});
Above code will get the HTML element with ID test and it will insert the string Prepend this string beforeBegin of the content of this div.
See the fiddle to play around: http://jsfiddle.net/PddU4/Prepend this string
EDIT 2012-02-16:
You need to listen to your proxies success and failure: (you could also implement a listener when loading your store or on update)
listeners: {
success: function( response, options ){
console.log(response);
},
failure: function( response, options ){
console.log(response);
},
}
EDIT BASED ON YOUR COMMENT:
First make sure you configured properly your successProperty and messageProperty in your reader. Then implement the listener where you want it to be, update, remove, add, exception etc. :
(configure the listener within your proxy object)
listeners : {
update : function(thisStore, record, operation ) {
console.log('Update happened');
console.log(record);
console.log(operation);
},
save : function() {
console.log('Save happened');
},
exception : function(dataproxy, type, action, options,response, arg) {
console.log('Error happened');
console.log(response);
doJSON(result.responseText);
},
remove : function() {
console.log("Record removed");
}
}
When you console.log(response), you will see the response object. This would be your actual JSON so you need to parse it (as in doJSON() method):
function doJSON(stringData) {
try {
var jsonData = Ext.util.JSON.decode(stringData);
Ext.MessageBox.alert('Success', 'Your server msg:<br />jsonData.date = ' + jsonData.message);
}
catch (err) {
Ext.MessageBox.alert('ERROR', 'Could not decode ' + stringData);
}
}
Please check out this AJAX tutorial: http://www.sencha.com/learn/legacy/Manual:Core:Ext.Ajax