Isomorphic React.js & iso-http - javascript

I'm building a react web application which I'd like to render both server side and client side. I've been working off isomorphic-react-template but I've used iso-http to make a query to my content server. My aim is to have the app when server-side query the content server directly and render the content to HTML; and to have the app when client-side to do a normal AJAX request for content.
Here's the code I'm using. It works great on the browser, but the server-side render doesn't include the data; I presume because the server-side render isn't waiting for the async http call to return before it compiles the HTML and sends it over:
componentDidMount: function() {
var id = this.getParams().id;
var classThis = this;
request
.get("http://content.example.com/things/" + id)
.end(function(response) {
response.body = JSON.parse(response.text);
if (response.ok) {
classThis.setState({ data: response.body });
} else {
classThis.setState({ data: null });
}
});
}
I know this is all fairly new stuff; but is there a known way to solve this problem, so that the server side renderer waits for certain async calls to complete before sending?

I've managed to get this working with react-async.
I've pulled out my async function like this so I can call it from componentDidMount and from the asynchronous getInitialStateAsync function that ReactAsync uses:
mixins: [ ReactAsync.Mixin ],
getInitialStateAsync: function(callback) {
this.getContent(function(state) {
callback(null, state)
}.bind(this))
},
componentDidMount: function() {
this.getContent(function(state) {
this.setState(state);
}.bind(this));
},
getContent: function(callback) {
var id = this.getParams().id;
request
.get("http://content.example.com/things/" + id)
.end(function(response) {
response.body = JSON.parse(response.text);
if (response.ok) {
callback({ error: {}, post: response.body })
} else {
callback({ post: {}, error: response.body });
}
});
}
Then in my server.jsx I'm rendering with the async functions:
ReactAsync.renderToStringAsync(<Handler />, function(err, markup) {
var html = React.renderToStaticMarkup(<Html title={title} markup={markup} />);
res.send('<!DOCTYPE html>' + html);
});
Obviously there is huge potential for cock up here (the whole page fails to render if the server isn't present) but this feels like the start of the right approach!

Related

vue js ajax inside another ajax is getting data but not rendering view

There is a situation that I have to get extra data after my first ajax (in mounted function) in vuejs, I have put the second ajax in if condition and inside success function of the first ajax!
It is working and I see data in Vue Devtools in chrome, but data is not rendered in view.
Pseudo Code:
var vm = new Vue({
el: '#messages',
data: {
participants: [],
active_conversation: '',
messages: []
},
methods: {
getParticipants: function () {
return this.$http.post('message/get-participants').then(
function (response) {
vm.participants = response.data.participants;
// if there is a conversation_id param in url
if (getUrlParameterByName('conversation_id')) {
// Second Ajax Is Called Here inside First Ajax
return vm.getConversationMessages (getUrlParameterByName('conversation_id')); // this ajax call is getting data but not showing in view
}
}
},
getConversationMessages : function(conv_id){
// Second Ajax Call to get Conversation messages
// and showing them , works onClick
return this.$http.post('message/get-messages/' + conv_id).then(
function (response) {
if (response.data.status == 'success') {
console.log(response.data.messages)
vm.messages = response.data.messages;
vm.$forceUpdate();
}
},
mounted: function () {
this.getParticipants()
}
})
The Second Ajax Call to get a specific conversation messages is responding to onclick event and showing messages, but when this function is used inside the First Ajax success response (getParticipants()), its getting data correctly nd I can see in DevTools VueJs Extension that messages are set but view does not show messages, I have tried vm.$set() but no chance.
Update:
The second Ajax is working with no errors and messages data property get filled (I checked Vue DevTools), The only problem is that view does not show the messages!! but when I do it manually by clicking on a conversation, second ajax is executed again and I can see messages!, I also tried vm.$forceUpdate() after second ajax with no chance.
Update2 html part(the bug is here!!)
<a vbind:id="conv.id" v-on:click="getMessages(conv.id)" onclick="$('#user-messages').addClass('active')">
the DOM is updated with messages with when you do the ajax request with only getConversationMessages and not placing
getConversationMessages in the success callback of the ajax request of getParticipants is the fact that an error is encountered at this line
this.participants = response.data.participants;
you are using a normal function in the success callback of the ajax request that's the reason this does not point to the vue instance
adnd this.participants gives you an undefined error. So use vm insteaad to point to the vue instance as you did in the rest of the program
vm.participants = response.data.participants;
Edit
var vm = new Vue({
el: '#messages',
data: {
participants: [],
active_conversation: '',
messages: []
},
methods: {
getParticipants: function () {
return this.$http.post('message/get-participants');
},
getConversationMessages : function(conv_id){
return this.$http.post('message/get-messages/' + conv_id);
}
},
mounted: function () {
this.getParticipants().then(function (response){
vm.participants = response.data.participants;
if (getUrlParameterByName('conversation_id')) {
return vm.getConversationMessages (getUrlParameterByName('conversation_id')); // this ajax call is getting data but not showing in view
}
}).then(function(response){
if (response.data.status == 'success') {
console.log(response.data.messages)
vm.messages = response.data.messages;
});
}
})
Call second http request after first is completed using http callback or you can use Promise too.
return this.$http.post(function(response){
// first call
}).then(function(response){
// Second call
})
new Vue({
el: '#messages',
data: {
participants: [],
active_conversation: '',
messages: []
},
methods: {
async getParticipants (id) {
var response = await this.$http.post('message/get-participants')
this.participants = response.data.participants
if (id) this.getConversationMessages(id)
},
async getConversationMessages (id) {
var response = this.$http.post('message/get-messages/' + id)
if (response.data.status === 'success') {
console.log(response.data.messages)
this.messages = response.data.messages;
}
}
},
created () {
this.getParticipants(getUrlParameterByName('conversation_id'))
}
})
The problem for me was in html, I added a custom onclick event to the div element previously and this event was conflicting with Vuejs events.

Jaspersoft visualise.js report export failing to produce file

I hope there is few among you who have experience with Jaspersoft Reports and their new visualise.js api
I have a problem with visualise.js not producing report export file. What happens is:
I am able to succsefully load the report through the visualise.js API, it loads and displays on my web page
Export controls load up successfully too, so I have dropdown with export file formats and a button to export the file.
When I click the export button though, the whole page reloads as if the export button was really a submit button and nothing happens.
Occasionally, the export will work and it will produce file. Though there is no pattern to when it will produce the file and when it will fail.
Below is the code I am using for this (I am using plain text auth for testing purposes):
visualize({
auth: {
name: "mylogin",
password: "mypass",
organization: "organization_1"
}
}, function (v) {
var $select = buildControl("Export to: ", v.report.exportFormats),
$button = $("#button"),
report = v.report({
resource: "/FPSReports/journal",
container: "#export",
params: {
"journal_ref": [ "<?php echo $reference; ?>" ],
},
success: function () {
button.removeAttribute("disabled");
},
error : function (error) {
console.log(error);
}
});
$button.click(function () {
console.log($select.val());
report.export({
// export options here
outputFormat: $select.val(),
// exports all pages if not specified
// pages: "1-2"
}, function (link) {
var url = link.href ? link.href : link;
window.location.href = url;
}, function (error) {
console.log(error);
});
});
function buildControl(name, options){
function buildOptions(options) {
var template = "<option>{value}</option>";
return options.reduce(function (memo, option) {
return memo + template.replace("{value}", option);
}, "")
}
var template = "<label>{label}</label><select>{options}</select><br />",
content = template.replace("{label}", name)
.replace("{options}", buildOptions(options));
var $control = $(content);
$control.insertBefore($("#button"));
//return select
return $($control[1]);
}
});
HTML:
<div class="grid">
<div class="grid-8"></div>
<div class="grid-8 center">Export</div>
<div class="grid-8"></div>
</div>
<div class="grid">
<div class="grid-24" id="export"></div>
</div>
The only parameter comes from URI segment (I am using codeigniter framework):
$reference = $this->uri->segment(3, 0);
I have found an answer that seems to work, and has resolved the issue. Posting it here in case anyone else has this specific problem like I did.
In brief:
After spending hours looking at console debug output I have realised that each time I tried to send a request for export a new session would be opened. Without logging out of the previous one. And apparently that is a no-no. I do not know JS very well but from what I understood there was session id mismatch in request. Please feel free to correct me here :)
The solution to this problem (or for example if you are having authentication issues with visualize.js) is very simple. Set the authentication in global config:
visualize.config({
auth: {
name: "superuser",
password: "superuser"
}
});
No matter if you are using tokens or plain text or whatever else auth is available through the api.
Then do your stuff wherever else on your website:
visualize(function (v) {
v("#container1").report({
resource: "/public/Samples/Reports/06g.ProfitDetailReport",
error: function (err) {
alert(err.message);
}
});
});
visualize(function (v) {
v("#container2").report({
resource: "/public/Samples/Reports/State_Performance",
error: function (err) {
alert(err.message);
}
});
});
Everything should work for you as it did for me. This works in version 5.6 and 6.1 of visualize.js.
Further reading and links from my research:
Token based authentication to Jasper reports failing when used with visualize.js
Visualize.js authentication error after second login
http://community.jaspersoft.com/questions/842695/visualizejs-authentication-error
http://community.jaspersoft.com/questions/845886/authentication-error-refresh-credentials-visualizejs
Code example (5.6):
http://jsfiddle.net/TIBCO_JS_Community/sozzq0sL/embedded/
Api samples (6.1):
http://community.jaspersoft.com/wiki/visualizejs-api-samples-v61
Api samples (5.6):
http://community.jaspersoft.com/wiki/visualizejs-api-notes-and-samples-v56
Really hope this will help someone new to Jaspersoft & visualize.js like me.

React Component JSON Callback Scope

I'm using generator-react-webpack to create a React web app. This web app relies on JSON feeds - one of which is hosted on a CDN that does not support JSONP and the CDN url is a subdomain of the webapp. Is there any way to return the JSON data from within the React Component?
Basic React Component:
var AppComponent = React.createClass({
loadData: function() {
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
console.log(data);
}.bind(this));
},
render: function(){
return ( ... );
}
});
I've tried a few solutions, and have come to the conclusion that I need to define my own callback on the JSON file like so:
JSON:
handleData({
"data": "hello World"
})
Is there a way for the handleData callback to be defined in the react component, or the response accessed from the react component? Any thoughts as to how I can get this to work are much appreciated. Thanks!
This looks like an odd way to do things, especially the part where you're using jQuery. That's a client-side utility to overcome not knowing where everything is and not having direct access to your elements. It makes no sense to use it when you're using React weith Webpack for bundling: React already knows where everything is (using refs) and Webpack means you can just use regular universal Node modules for everything that you need to do.
I'd recommend using something like, using request or a similar universal fetch API:
// loadData.js
var request = require('request');
var loadData = function(urlYouNeed, handler) {
request(urlYouNeed, function(error, response, body) {
if (error) {
return handler(error, false);
}
// do anything processing you need on the body,
var data = process(body);
handler(false, data);
};
So: just a module you can require in any component you define with require('./loadData'). And then in your actual component you do this:
var loadData = require('./loadData');
var AppComponent = React.createClass({
getDefaultProps: function() {
return {
jsonURL: "cdn://whateverjson.json"
};
},
getInitialState: function() {
loadData(this.props.jsonURL, this.updateData);
return {
data: []
}
},
updateData: function(err, data) {
if (err) {
return console.error(err);
}
data = secondaryEnsureRightFormat(data);
this.setState({ data: data });
},
render: function(){
var actualThings = this.state.data.map((entry, pos) => {
return <Whatever content={entry} key={entry.dontUseThePosVariableUpThere}/>
});
return (
<div>
...
{actualThings}
...
</div>
);
}
});
Much cleaner.
If I understand correctly the question, you only have to change your loadData this way :
loadData: function() {
var c = this
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
c.handleData(data)
});
},
handleData: function(data) {
/* Implement here the function to handle the data */
},

Cannot get response content in mithril

I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://localhost:3000/store/all"});
}
};
var Component = {
controller: function() {
var stores = Model.getAll();
alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
alert(stores()); // Alert box: undefined
},
view: function(controller) {
...
}
};
After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:
[{"name":"Mike"},{"name":"Zeza"}]
I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:
var stores = m.prop([]);
Before the model and changing the request to:
return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);
I might be doing something wrong because I get the same result.
The objective is to get the data from the response and send it to the view to iterate.
Explanation:
m.request is a function, m.request.then() too, that is why "store" value is:
"function (){return arguments.length&&(a=arguments[0]),a}"
"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.
Working sample:
You can start playing with this sample, and implement what you need:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
}
};
var Component = {
controller: function() {
var records = Model.getAll();
return {
records: records
}
},
view: function(ctrl) {
return m("div", [
ctrl.records().records.map(function(record) {
return m("div", record.Name);
})
]);
}
};
m.mount(document.body, Component);
If you have more questions, feel free to ask here.

PhoneGap/Cordova with client-side routing?

I've inherited a Cordova/PhoneGap app running Cordova 3.4. My first task was to implement a Client-Side Routing framework to make it easier to navigate between pages. I chose Flatiron Director as my client-side router, but when I went to implement it I started to get weird functionality out of the app.
My first router setup:
var routing = {
testHandler: function(){
console.log('Route ran');
},
routes: function(){
return {
"/testhandler": testHandler
}
}
};
console.log('Routes added');
The routes are added (at least based on the console output). When I attempt to hit the /testhandler hash, I receive a "Failed to load resource: file:///testhandler" error when I set window.location.hash to "/testhandler". I noticed the "Route ran" statement was never printed.
My next attempt was just using the hashchange event with jQuery.
$(window).on('hashchange', function(){ console.log('Ran'); });
On this attempt, regardless of what I change the hash to, I see the 'Ran' output, but I still receive the "Failed to load resource: " error.
Is this a problem with PhoneGap/Cordova? Or our implementation? Is it just not possible to use client-side routing with Cordova? What am I doing wrong?
I know that this doesn't answer your question directly but you may consider making your own provisional router. This may help you to debug your app and to figure out what's the problem.
Something like this for example:
var router = (function (routes) {
var onRouteChange = function () {
// removes hash from the route
var route = location.hash.slice(1);
if (route in routes) {
routes[route]();
} else {
console.log('Route not defined');
}
};
window.addEventListener('hashchange', onRouteChange, false);
return {
addRoute: function (hashRoute, callback) {
routes[hashRoute] = callback;
},
removeRoute: function (hashRoute) {
delete routes[hashRoute];
}
};
})({
route1: function () {
console.log('Route 1');
document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
},
route2: function () {
console.log('Route 2');
document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
}
});

Categories