React.js key generation - hashmap

I've a problem with the Reconciliation algorithm using a set of key (without duplicates). The snippet of code is similar to the examples:
`
var ResourceTable = React.createClass({
getInitialState: function() {
return {data: [{"rid": "Ciao ", "id": 10}, {"rid": "Mondo!", "id": 2}]};
},
componentDidMount: function() {
self = this;
self.setState({data: [{"rid":"first", "id": 3},{"rid":"second", "id": 1},{"rid":"third", "id": 2}]});
},
render: function() {
var commentNodes = this.state.data.map(function (resource, index) {
return (
<Resource key={resource.id} rid={resource.rid}/>
);
});
return(
<table>
{commentNodes}
</table>
);
}
});
`
The first time that the object is rendered everything works fine (for every value of the resource.id). The second time I've an unattended behavior: sometimes every element is correctly rendered and sometimes not, I made a lot of attempts, but I cannot find an explanation.
The case that cause the error is:
First rendering keys: [10,2]
Second rendering keys: [3,1,2]
The result is that only two element are rendered during the second rendering.

React is very sensitive if you are rendering HTML which is mutating in browser. This is the case with <table>, which can be created like this:
<table>
<tr><td>Cell</td></tr>
</table>
But in fact browsers are changing it to:
<table>
<tbody>
<tr><td>Cell</td></tr>
</tbody>
</table>
After this operation DOM and React Virtual DOM differs and triggers errors like yours. To fix it just change:
return (
<table>
{commentNodes}
</table>
);
into:
return (
<table>
<tbody>{commentNodes}</tbody>
</table>
);

Related

Display json data stored into array in table format using React

I have configured a react website to receive json data and store it into an array in the format depicted in the attached image. How would I go about displaying this information in a table format?json data stored in array
If you don't want to use property names, you could do something like that :
import React, { Component } from "react";
import { render } from "react-dom";
const App = () => {
const data = [
{ id: 0, value: "item 1" },
{ id: 1, value: "item 2" },
{ id: 2, value: "item 3" }
];
const keys = Object.keys(data[0]);
return (
<div>
<table>
<thead>
{keys.map(key => {
return (
<th>
<td>{key}</td>
</th>
);
})}
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr>
{keys.map(key => (
<td>{item[key]}</td>
))}
</tr>
);
})}
</tbody>
</table>
</div>
);
};
render(<App />, document.getElementById("root"));
Note that all of your items need to have the same properties (here 'id' and 'value') for this to work.
Here is the repro on stackblitz
If you need something better then you should look for a package made for this, there's plenty on internet.

Using Ember Data to load data async from node sever

My Model :
App.Contacts = DS.Model.extend({
name : DS.attr('string'),
number : DS.attr('number')
});
This is how i save a record :
App.AddController = Ember.Controller.extend({
actions : {
addContact : function(){
var post = this.store.createRecord('Contacts',{
name : this.get('name') ,
number : this.get('number')
});
post.save();
}
}
});
Acc to Ember's offical guide, this would send a POST request to /Contacts , so to handle it, i used this in nodejs/expressjs
app.post('/contacts',function(req,res){
posts.push( req.body);
console.log(posts);
res.send({status: 'OK'});
});
Now i wish to retrieve it, into another template called all so i used :
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.find('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});
Acc to Emberjs guides, model hook supports promises out-of-the-box . so i assumed this should work.
My template :
<script type="text/x-handlebars" id="all" >
Hello
<table>
{{#each contact in contactList}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
</table>
</script>
Question
But the model returns nothing, i understand that this.store.find('Contacts') doesn't return a javascript array, but essentially and object , implimenting Ember.Enumerable
But on the server side, the posts is an javascript array, therefore there might be an type mismatch between then. how to resolve this?
EDIT:
To avoid any confusions in client side Ember code , This works properly, so there is some problem with the round trip to server.
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.all('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});
If you could provide a jsfiddle, it be nice. I'm not sure whether contactList is defined or not and whether the alias for that controller is actually defined. So based on what I see, I think the problem is you're iterating over a controller that does not have the model properly defined.
I'd suggest trying to do:
{{#each}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
If you really want to use the contactList controller, then you need to make sure that the App.AllController "needs" the contactListController.
App.ContactListController = Ember.ArrayController.extend({}) // needs to be an array controller
App.AddController = Ember.ArrayController.extend({
needs: ["contactList"], // controller's used within this controller
contactList: Ember.computed.alias("controllers.contactList"), // needed to iterate over the model how you're doing it.
Both of these solutions should work assuming your data is actually loaded in Ember Data. You might want to check the "data" tab on the ember-data console. If you don't have that browser extension installed, do it. It's incredibly useful.
If all else fails, try logging to verify expected values using {{log contactList}}
Good luck

YUI3 Datatable loaded with JSON displays only no results to display (Scala/Play 2.1)

I am new to YUI but I veteran of JQuery UI. So this one has me stumped. I cannot get my Datatable to render with the Rest service. I have two version of the code. One that I use the captured JSON object from the service as just a data object and a local datasource. That one works fine. When I attempt to switch to the GET plugin and get it from the service. It just never renders.
My local example:
#main("Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-local", "datasource-jsonschema", "datatable-datasource", function (Y) {
var data = [
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
];
var localDataSource = new Y.DataSource.Local({source:data});
localDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var simple = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
simple.plug(Y.Plugin.DataTableDataSource, {
datasource:localDataSource
});
simple.render("#dataGrid");
simple.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
<div id="dataCheckArea">
<h3>RAW DATA AREA</h3>
<ul>
#records.map {record =>
<li>#record.toString</li>
}
</ul>
</div>
}
My REST Service example:
#main("Welcome to Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function (Y) {
var dataSource = new Y.DataSource.Get({
source:"http://localhost:9000/reviewRecords?q=query"
});
dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var dataGrid = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
dataGrid.plug(Y.Plugin.DataTableDataSource, { datasource:dataSource });
dataGrid.render("#dataGrid");
dataGrid.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
** edited because the original submission lost my second code block.
The problem wasn't with my javascript code. The issue was with how I was sending the response. The YUI framework expects that the response will be wrapped in a callback function. When I changed my response to give a JSONP response with the callback it all started working.
YUI.Env.DataSource.callbacks.yui_3_11_0_1_1379097239018_187([
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
])
I did this by using a JSONP call in the method response from Scala/Play 2.1
def reviewRecords(q: String, callback: String) = Action {
val reviewRecords = reviewRecordsService.currentReviewRecords
Ok(new Jsonp(callback, Json.toJson(DataTablesReturnObject(reviewRecords.size, reviewRecords.toArray)))).as("application/json")
}
I am going to edit the title of my original question to include the keywords for Play 2.1 and Scala because this ends up being a little different than a Java response.

Unable to get Meteor-Pagination to work

I am trying to add pagination support to my meteor app but my template shows a blank page as soon as I add the {{{pagination}}} tag in my template. There are no errors in the log.
My client js (routing info) looks like this
Meteor.Router.add({
'/': function () {
var user;
if (Meteor.loggingIn()) {
console.log('home: loading');
return 'loading';
}
user = Meteor.user();
if (!user) {
console.log('homer: signin');
return 'user_signin';
}
// start on 'start' page
console.log('home: start');
return 'page';
},
'/landing': 'landing',
'*': 'not_found',
'/landing/:page': function (page) {
Session.set('page', page) ;
return 'landing' ;
}
});
My Landing.js looks like this
Template.userList.pagination = function () {
return Pagination.links('/landing', Meteor.users.find({}).count(), {currentPage: Session.get('page'), perPage: 8}) ;
}
My landing template is as follows:
</thead>
<tbody>
{{#each users}}
{{> user}}
{{/each}}
{{{pagination}}}
</tbody>
</table>
I see a couple things with the code posted.
I don't know much about the Pagination addin but it looks like you have it inside the table tag and according to this (https://github.com/egtann/meteor-pagination) it renders a div. I believe that would be invalid.
In your routes you have the wildcard '*' before the 'landing/:page'. I believe it would match that one first. Should have the '*' be the last route you add.

When to call YUI destroy?

When should destroy be called? Does it ever get called automatically by YUI lifecycle? Does the page unload cause the YUI lifecycle to call destroy on all objects created during the page processing? I have been working under the assumption that I need to make all my own calls to destroy but that gets hairy when ajax calls replace sections of code that I had progressively enhanced. For example:
<div id="replaceMe">
<table>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
</table>
<script>
YUI().use('my-lib', function(Y) {
Y.mypackage.enhanceTable("replaceMe");
});
<script>
</div>
The my-lib module basically adds a click handler and mouseover for each row:
YUI.add('my-lib', function(Y) {
function EnhancedTable(config) {
EnhancedTable.superclass.constructor.apply(this, arguments);
}
EnhancedTable.NAME = "enhanced-table";
EnhancedTable.ATTRS = {
containerId : {},
onClickHandler : {},
onMouseoverHandler : {},
onMouseoutHandler : {}
};
Y.extend(EnhancedTable, Y.Base, {
_click : function(e) {
//... submit action
},
destructor : function() {
var onClickHandler = this.get("onClickHandler"),
onMouseoverHandler = this.get("onMouseoverHandler"),
onMouseoutHandler = this.get("onMouseoutHandler");
onClickHandler && onClickHandler.detach();
onMouseoverHandler && onMouseoverHandler.detach();
onMouseoutHandler && onMouseoutHandler.detach();
},
initializer : function(config) {
var container = Y.one("[id=" + this.get("containerId") + "]");
this.set("container", container);
this.set("onMouseoverHandler", container.delegate("mouseover",
this._mouseover, "tr", this ));
this.set("onMouseoutHandler", container.delegate("mouseout",
this._mouseout, "tr", this ));
this.set("onClickHandler", container.delegate("click",
this._click, "tr", this ));
},
_mouseout : function(e) {
e.currentTarget.removeClass("indicated");
},
_mouseover : function(e) {
e.currentTarget.addClass("indicated");
}
});
Y.namespace("mypackage");
Y.mypackage.enhanceTable = function(containerId) {
var enhancedTable new EnhancedTable({containerId:containerId});
};
}, '0.0.1', {
requires : [ 'base', 'node' ]
});
The click handler would submit a request back to my application that would change the page. Do I need to remember all the enhancedTable objects and have an onunload handler call the destroy method of each? Or does the YUI framework take care of this?
The last part of this quesiton is, I also have code outside of this that replaces the whole table by replacing the content of the <div id="replaceMe">. In doing so, the script would get re-run and augment the new <table> with a new EnhancedTable. Do I need to remember the old table, and destroy it before the new table clobbers it?
Instead of setting handlers as attributes I'd store them all in an array like this:
this._handlers = [
container.delegate("mouseover", this._mouseover, "tr", this ),
container.delegate("mouseout", this._mouseout, "tr", this ),
container.delegate("click", this._click, "tr", this )
];
Then add a destructor method that does the following
destructor : function() {
new Y.EventTarget(this._handlers).detach();
}
It accomplishes the same thing but with way less work on your part!
Ideally instead of running this against each table you'd attach all your delegates to #replaceMe so that it wouldn't need to be recreated each time you changed the content, no matter where that happened from.
YUI won't automatically call .destroy() for you on unload, it will clean up DOM subs though. The above is extra credit that's really only necessary if you are going to be destroying the object yourself.

Resources