I"m trying to pull images into a React List module using a JSON and can't figure out what I'm doing wrong.
This FIDDLE is supposed to grab two images from my server.
Code:
var Playlist = React.createClass({
render() {
var playlistImages = [];
$.getJSON('http://k1r.com/json/playlist_tn.json', function(data){
playlistImages = data;
});
return (
<List list={playlistImages.images} />
)
}
});
UPDATED FIDDLE
I'm not sure you can use modules directly in JSFiddle, but apart from that the main issue is that you are fetching some asynchronous data directly in your render method and React isn't going to wait on that to finish before rendering your List.
The suggested approach (via the docs: https://facebook.github.io/react/tips/initial-ajax.html) is to make your data request inside of the componentDidMount or componentWillMount lifecycle methods then use setState() to trigger a re-render when the data has been received, which should then correctly render your List.
Related
I am trying to load a GeoJSON file and to draw some graphics using it as a basis with D3 v5.
The problem is that the browser is skipping over everything included inside the d3.json() call. I tried inserting breakpoints to test but the browser skips over them and I cannot figure out why.
Code snippet below.
d3.json("/trip_animate/tripData.geojson", function(data) {
console.log("It just works"); // This never logs to console.
//...all the rest
}
The code continues on from the initial console.log(), but I omitted all of it since I suspect the issue is with the d3.json call itself.
The signature of d3.json has changed from D3 v4 to v5. It has been moved from the now deprecated module d3-request to the new d3-fetch module. As of v5 D3 uses the Fetch API in favor of the older XMLHttpRequest and has in turn adopted the use of Promises to handle those asynchronous requests.
The second argument to d3.json() no longer is the callback handling the request but an optional RequestInit object. d3.json() will now return a Promise you can handle in its .then() method.
Your code thus becomes:
d3.json("/trip_animate/tripData.geojson")
.then(function(data){
// Code from your callback goes here...
});
Error handling of the call has also changed with the introduction of the Fetch API. Versions prior to v5 used the first parameter of the callback passed to d3.json() to handle errors:
d3.json(url, function(error, data) {
if (error) throw error;
// Normal handling beyond this point.
});
Since D3 v5 the promise returned by d3.json() will be rejected if an error is encountered. Hence, vanilla JS methods of handling those rejections can be applied:
Pass a rejection handler as the second argument to .then(onFulfilled, onRejected).
Use .catch(onRejected) to add a rejection handler to the promise.
Applying the second solution your code thus becomes
d3.json("/trip_animate/tripData.geojson")
.then(function(data) {
// Code from your callback goes here...
})
.catch(function(error) {
// Do some error handling.
});
Since none of the answers helped, I had to find the solution on my own that works. I am using v4 and have to stick with it. The problem was (in my case) that d3.json worked the first time, but did not work the second or third time (with a HTML dropdown).
The idea is to use the initial function, and then simply to use a second function with
let data = await d3.json("URL");
instead of
d3.json("URL", function(data) {
Therefore, the general pattern becomes:
async function drawWordcloudGraph() {
let data = await d3.json("URL");
...
}
function initialFunction() {
d3.json("URL", function (data) {
...
});
}
initialFunction();
I have tried several approaches, and only this worked. Not sure if it can be simplified, please test on your own.
I am new to office 365 word JavaScript API. I am trying to send a Json object to a dialog from the parent using the dialog api. But I couldn't find a better solution for that. I have found it is possible to send a Json object from the dialog to the parent using below code snippet.
Office.context.ui.messageParent
can someone give me a good solution with a code snippet to solve this problem?
You can try something like that
In parent web page (the actual add-in) javascript code
Office.context.ui.displayDialogAsync(url, options, function(result) {
var dialog = result.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function(args){
dialog.close();
var json = JSON.parse(args.message);
//do what ever you need to do...
});
});
NOTE: for the sake of simplicity I omitted "error checks" if callback function receive error result. You should take care of that as well.
The web page that is opened at url will have a function for pushing back the json object after representing it as a string
var asString = JSON.stringify(myObj);
Office.context.ui.messageParent(asString);
Of course the webpage opened in the dialog window must also reference Office.js.
Here is the documentation link for this so-called dialogAPI https://dev.office.com/reference/add-ins/shared/officeui
Edit:
the original question is to send data from parent to children
If you need to send info to the page opened in dialogAPI. I suggest your append query parameters to url. You can stringify your Json object and pass it. This is not very clean thought.
Standardized way to serialize JSON to query string?
You can send JSON data or object back to your parent easily.
This code snippet should be in your child page's(Dialog page) JS file.
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
$('#btnLogin').click(submit);
});
};
function submit() {
// Get and create the data object.
var email = $('#txtEmail').val();
var password = $('#txtPassword').val();
var data = {
email: email,
password: password
}
// Create the JSON and send it to the parent.
var json = JSON.stringify(data);
Office.context.ui.messageParent("json");
}
})();
See here: https://dev.office.com/docs/add-ins/develop/dialog-api-in-office-add-ins
Find section "Passing information to the dialog box".
Two primary ways:
Add query parameters to the URL
Store the information somewhere that is accessible to both the host window and dialog box, e.g. local storage
I am trying to parse some json with Handlebars on my website. I don't get any errors but also don't get any content. I've developed my own rest point to return a json response and I think my problem might be there somewhere, but you can see the response in the code.
http://codepen.io/anon/pen/Czdxh
$(document).ready(function(){
var raw_template = $('#post-template').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Retrieve the placeHolder where the Posts will be displayed
var placeHolder = $("#all-posts");
// Fetch all Blog Posts data from server in JSON
$.getJSON("https://instapi-motleydev.rhcloud.com/liked",function(data){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
placeHolder.append(html);
});
});
});
Thanks for any help!
The problem was I was getting an array response from the server and needed to adapt my template to include the {#each this} syntax. Also switched my getJSON to a simple get and looped over the reaction that way and tossed the $.each handler.
I have been working with Famo.us just for a short while but now I am in need of consuming some JSON. In jQuery I would use the getJSON method to make the JSON call and get the data back in an object. Is there a way to do this in pure Famo.us? I ask because I have only found examples of jQuery being added to the app to make that JSON call. I am not sure that this is the best practice so I figured maybe someone could point me in the right direction.
$.getJSON('data/data.json', function(json) {
$.each(json, function(key,data){
seriesArr.push({
name: data.name,
y: data.Count,
drilldown: data.name
});
});
});
There is a Utility function in famo.us for loading an URL: Utility.loadURL
(https://famo.us/docs/utilities/Utility)
var Utility = require('famous/utilities/Utility');
Utility.loadURL('http://example.com', function (content) {
// Check response
if (!content) {
return;
}
// Consume response
var parsedContent = JSON.parse(content);
...
});
You can certainly use jQuery for making requests in Famo.us. Famo.us is designed as the presentation layer of the application. It does not care how the data gets in or out.
Just some things to keep in mind. When making requests, Try to time them such that all animation is complete. A request no matter the library will cause stuttering.
For instance using the setTransform callback method of a StateModifier..
state.setTransform(transform, transition, function(){
// Make request
});
So to sum things up, You are on the right path. With vanilla Famo.us you are free to make requests with whichever other library you wish. Just do so in a timely manner!
Good Luck!
I am having difficulty replacing the content of an HTML element with a JSON object property. Here's my code:
url = '/blah/blah-blah';
data = $.getJSON(url);
$(this).parent('.status').replaceWith(data.content);
Now, I know that the correct JSON object is being returned and that it includes a properly formatted property called 'content'. (I am displaying it in the console). Secondly, I know that I am selecting the correct element to replace. (If I replace data.content with 'bingo!' I see the text displayed on screen.)
When I run the code above, however, I see the content of my element replaced with nothing. What am I doing wrong?
Note that I tried replacing data.content with data.responseJSON.content, but that didn't help.
Thanks!
You need to use a callback,
url = '/blah/blah-blah';
$.getJSON(url, function(data) {
$("some selector").parent('.status').replaceWith(data.content);
})
In your example, $.getJSON doesn't return anything meaningful -- probably just 'undefined'. Meanwhile, it makes your request. When getJSON succeeds, the result is passed to a handling function which does things with it. If you don't provide a callback, nothing will happen when you get a response back from the server.
or if you don't want to use a new selector, you can save $(this).
url = '/blah/blah-blah';
item = $(this)
$.getJSON(url, function(data) {
item.parent('.status').replaceWith(data.content);
})
The AJAX call is asynchronous, so the content hasn't arrived yet when you try to use it. When you display it in the console, you can't do that fast enough to see that the response doesn't arrive immediately.
Use a callback in the getJSON call to handle the data when it arrives:
url = '/blah/blah-blah';
$.getJSON(url, function(data) {
$(this).parent('.status').replaceWith(data.content);
});
Your code is executing before the .getJSON(url) call is completing. Try specifying a success handler like so:
$.getJSON(url, function(data) {
$(this).parent('.status').replaceWith(data.content);
});