I'm trying the example in reactjs tutorial https://facebook.github.io/react/docs/tutorial.html to read the json from server(file). But, my "componentDidMount" is not getting called.
Below is the code:
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function() {
return {data: {}};
},
componentDidMount: function() {
this.loadCommentsFromServer();
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.content.map(function(comment) {
return (
<Comment pageName={comment.xyz} key={comment.id}>
{comment.abc}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
<h2 className="commentpageName">
{this.props.pageName}
</h2>
<p> {this.props.children} </p>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/api/comments" />, document.getElementById('content'));
Please check the way I have initialized the data(data: {})
The "componentDidMount" gets called when the json is of the following type(Just the way in the tutorial):
[ {"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"} ]
But the json format I want is:
{
content: [
{"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"},
{"id": "3", "xyz": "xyz3", "abc": "abc3"}],
"totalPages":3,
"totalElements":10,
"last":true
}
Let me know in what conditions the componentDidMount doesn't get called. Please help.
In the "Networks" console of chrome developer tools, I don't see the call made to my json file.
When I added logs in my program, I see that getInitialState() gets called first, then render, then the error "Uncaught TypeError: Cannot read property 'data' of null" is shown.
I think your componentDidMount() is not called because your render code inside <CommentList> does not work on first render, because data is empty, and this.props.data.content probably does not exist, therefore your render fails.
What you probably should do is change this:
var commentNodes = this.props.data.content.map(function(comment) {
To this:
var commentNodes = [];
if (this.props.data.content) {
commentNodes = this.props.data.content.map(function(comment) {
...
}
componentDidMount() is always called after the first render (and not in subsequent renders)
Related
I need to show data from a json response from get request. Vue part of my code is :
<script type="text/javascript">
var vm = new Vue({
el: '#app2',
delimiters: ['[[',']]'],
data: {
masa_data: {},
},
mounted: function() {
polling1=setInterval(function() {
axios.get('/order')
.then(function(response) {
vm.$data.masa_data = response.data;
})
}, 1000);
},
beforeDestroy () {
clearInterval(this.polling1)
}
});
</script>
masa_data comes from axios as below:
{ "Bahçe1": { "A": { "1": { "kisi_sayisi": "2", "siparisler": [ {
"adet": 2, "bolum": "drink", "satir": "Açık Çay" }, { "adet": 1,
"bolum": "tatli", "satir": "Kaymaklı Ekmek Kadayıfı" } ] },
When i want to show, for example, value of "kisi_sayisi", I could not figure out what to put inside html code below:
<p class="card-text">[[masa_data]]</p>
Try this.
<p class="card-text" v-if="Object.values(masa_data).length>0">[[masa_data.Bahce1.A['1']['kisi_sayisi'] ]]</p>
https://codepen.io/Pratik__007/pen/QWbjOxE?editors=1010
I'm trying to get a simple value out of my json string. It seems to be harder than I thought. How can I reach for example the 'name' of the first ModuleAction object in the following JSON (the first array is called 'data'):
[
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
Here's my best attempt:
data[0].ModuleActionModuleController[0].id
But I've got the error:
add:93 Uncaught TypeError: Cannot read property '0' of undefined
at Object.success (add:93)
at j (jquery-2.1.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.1.0.min.js:2)
at x (jquery-2.1.0.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-2.1.0.min.js:4)
Any idea what I'm doing wrong? :)
EDIT
Here's the ajax function that returns the data JSON string:
$(function() {
$('#PageModuleId').on('change', function(){
var formData = $('#PageAddForm').serialize();
// POST to server
$.ajax({
type: 'POST',
url: '<?php echo $this->here; ?>',
dataType: 'text',
data: formData,
success: function(data){
console.log(data[0].ModuleActionModuleController[0].ModuleAction.name);
}
});
});
});
How can I reach for example the 'name' of the first ModuleAction
object in the following JSON?
It appears to me that you are just missing the next child element: ModuleActionModuleController.ModuleAction.name
$(document).ready(function() {
var obj = jQuery.parseJSON( '{"ModuleController":{"id":"3"},"ModuleActionModuleController":[{"id":"4","module_action_id":"1","module_controller_id":"3","ModuleAction":{"id":"1","name":"Overzicht","action":"index"}},{"id":"5","module_action_id":"2","module_controller_id":"3","ModuleAction":{"id":"2","name":"Detail","action":"view"}}]}' );
//alert( obj.ModuleActionModuleController[0].ModuleAction.name );
document.body.innerHTML = obj.ModuleActionModuleController[0].ModuleAction.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works for me:
var JSON = {
"data": [
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
};
alert(JSON.data[0].ModuleActionModuleController[0].ModuleAction.id);
This is the JSON file ..
Using angular js controller and view how can I parse this json and display the drop1 and drop2 values of respective technology in drop down menu.getting the JSON data using http get.
Thanks in advance
{
"technology": [
{
"id": "AKC",
"detail": {
"drop1": [
{
"id": "AKC-lst-1231"
},
{
"id": "AKC-lst-1232"
},
{
"id": "AKC-lst-1233"
}
],
"drop2": [
{
"id": "T_AKC_live"
},
{
"id": "T_AKC_Capt"
},
{
"id": "T_AKC_live1"
}
]
}
},
{
"id": "MET",
"detail": {
"drop1": [
{
"id": "MET-2st"
},
{
"id": "MET-34"
}
],
"drop2": [
{
"id": "sd-232"
},
{
"id": "sd-121"
}
]
}
}
]
}
Please consider this example:
<!DOCTYPE html>
<html ng-app="postExample">
<head>
<script data-require="angular.js#1.2.22" data-semver="1.2.22" src="https://code.angularjs.org/1.2.22/angular.js"></script>
<script src="usersController.js"></script>
<script src="userRepoService.js"></script>
</head>
<body ng-controller="UsersController">
<h1>Post Angular Example</h1>
<select id="UserSelector" style="width: 100%;">
<option ng-repeat="user in users" value="{{user.id}}">{{user.login}} </option>
</select>
</body>
</html>
userRepoService.js
(function(){
var userRepoService = function($http){
var getUsers = function(username){
return $http.get("https://api.github.com/users")
.then(function(response){
return response.data;
});
};
return {
get: getUsers
};
};
var module = angular.module("postExample");
module.factory("userRepoService", userRepoService);
}());
Controller:
(function(){
var app = angular.module("postExample",[]);
var UsersController = function($scope, userRepoService){
var onFetchError = function(message){
$scope.error = "Error Fetching Users. Message:" +message;
};
var onFetchCompleted = function(data){
$scope.users =data;
};
var getUsers = function(){
userRepoService.get().then(onFetchCompleted,onFetchError);
};
getUsers();
};
app.controller("UsersController", UsersController);
}());
You can directly call $http service, and get that response inside success data parameter.
CODE
$http.get("test.json").
success(function(data, status, headers, config) {
//get data and play with it
}).
error(function(data, status, headers, config) {
alert("Error fetching data");
// log error
});
Hope this could help you, Thanks.
I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which seems to be found, but when trying to pass the data to the front end, or even alert it, is it alerting as []
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
}, function(error) {
//handle error here
});
alert(JSON.stringify($scope.countries));
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
Try this:
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
//handle error here
});
Alert should go in the callback.
This should do it
$http.get('/resources/data/countries-report.json').success(function(data) {
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}).error(function(error) {
alert('error');
});
also this equivalent would work
$http.get('/resources/data/countries-report.json').then(function(data) {
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
alert('error');
});
Edit --
Instead of $http.get('/someUrl', sucessCallback, errorCallback) it should be either
$http.get('/someUrl').success(successCallback).error(errorCallback)
or
$http.get('/someUrl').then(successCallback, errorCallback)
see docs
Because $http.get is asynchronous alert should be moved in the successCallback function, to ensure that $scope.countries=data is executed before calling alert.
$http.get is an async function. when you try alert(JSON.stringify($scope.countries)); $scope.countries is equals to []. You must wait for server response before using data.
Try to do your alert into success function
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
//handle error here
});
I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON