ReactJS fetch JSON API Data -- The correct way? - json

I have been fighting with ES6 trying to come up with, what should be, a pretty straightforward operation. I want to call JSON API data for Bitcoin from one of the three following websites:
https://cryptowat.ch
https://coinmarketcap.com/
https://www.cryptocompare.com/
All three sites API endpoints go straight to the price I want and I think this may be the problem. There is no array of data, just the specific price. In my example using #3 above, the only object is "USD". That being said, I think I'm overthinking the process as getting into APIs with much more data and arrays of data -- I have accomplished using ReactJS.
Trying to reach a single endpoint that shows up as the "State" in the React DOM Inspector as "USD" and is pulling in the correct price, I cannot get the price to render on the page even though ReactJS is seeing it and capturing it.
My code:
var BitcoinApp = React.createClass({
getInitialState: function() {
return {
"USD": []
}
},
componentDidMount: function() {
var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(result) {
th.setState({
USD: result.data.USD
});
})
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<span>
{this.state.USD.map(function(Data) {
return (
<div key={Data.USD} className="testbtc">
<p>{Data.USD}</p>
</div>
);
})}
</span>
)
}
});
ReactDOM.render(<BitcoinApp source="https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&e=Coinbase" />, document.querySelector("#btcPrice"));
I will mention that I have done a lot of research into this and have found a lot of answers -- all different! Everyone knows the ReactJS docs are severely outdated so finding the right path with ReactJS is difficult to say the least. Also, I'm using "axios" to "GET" the API data as I've read that "fetch" isn't globally supported yet? Is this still the case in 2017?
Using the above method, I can see this in the Inspector:
But when I go over to the "Console" portion of the inspector, I'm told that "this.state.USD.map is not a function".
I feel like I'm right on the cusp of solving this task, but I think I'm getting something wrong with the mapping of the promise.

the problem is that:
th.setState({
USD: result.data.USD
});
is seting not iterable object. I mean that this.state.USD.map is not a function means that USD is not an array (and you can see this in console).
Try this to see what happens:
th.setState({
USD: [result.data.USD]
});
However tho, you wrote:
There is no array of data, just the specific price.
then I think the best solution is to change just the render method and initial state:
render: function() {
return (
<span>
<div className="testbtc">
<p>{this.state.USD}</p>
</div>
</span>
)
}
getInitialState: function() {
return {
"USD": "",
}
},

Related

vue.js json object array as data

aye folks!
I'm currently learning to do stuff with vue.js. unfortunately i'm stuck atm. what i want to do is sending a request to my sample API which responds with a simple json formatted object.
I want to have this object as data in my component – but it doesn't seem to do that for whatever reason.
Ofc i tried to find a solution on stackoverflow but maybe i'm just blind or this is just like the code other people wrote. i even found this example on the official vue website but they're doing the same thing as i do .. i guess?
btw. When i run the fetchData() function in a separate file it does work and i can access the data i got from my API. no changes in the code .. just no vue around it. i'm really confused right now because i don't know what the mistake is.
code:
var $persons = [];
and inside my component:
data: {
persons: $persons,
currentPerson: '',
modal: false
},
created: function() {
this.fetchData()
},
methods: {
fetchData: function () {
var ajax = new XMLHttpRequest()
ajax.open('GET', 'http://api.unseen.ninja/data/index.php')
ajax.onload = function() {
$persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}
ajax.send()
}
},
[...]
link to the complete code
First, make sure that the onload callback is actually firing. If the GET request causes an error, onload won't fire. (In your case, the error is CORS-related, see this post suggested by #Pradeepb).
Second, you need to reference the persons data property directly, not the $persons array that you initialized persons with.
It would look like this (inside your fetchData method):
var self = this;
ajax.onload = function() {
self.persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}

Angular Conditional Views?

I have inherited a mess of a Angular project. I've never really messed with Angular too much but know MVC well enough to feel like I can learn. My question is I have a property of a JSON object that I want to return a different views for. (one is an archived state and one is a non-archived state) As they both have different view templates, how would I return the non-archive template if the json.status == 'archived'
I have the following as my current StateProvider's templateURL property.
templateUrl: appConfig.viewPath + 'non-archived.html?v=' + appConfig.version
should I just return multiple template urls here? Or do I have to create a whole new url path?
Thanks!
I've gone down this road a few times, I don't think I've found the optimal way yet, but I've learned a few things.
It really all depends on when you have access to your json-object. You can pass a function to templateUrl, and send in a service.. (A service that returns your current json-object could be great, but how would you update it? Probably when you change route right? Then you have a egg-hen problem. You can't decide route until you have the json-object, but you don't have the json-object until you change route.)
But IF you have access to the json-object you could do something like this:
templateUrl: function(){
var tpl = (json.status == 'archived') ? 'archived.html?v=' : 'non-archived.html?v=';
return appConfig.viewPath + tpl + appConfig.version
}
But my guess is that you don't have access to the json-object until after the route has loaded.
Then I'd say the easiest way (but maybe not so pretty) is to have just one template. $scope.json = json in the controller:
<div ng-if="json.status == 'archived'">
<h1>ARCHIVED</h1>
...
</div>
<div ng-if="json.status != 'archived'">
<h1>NOT ARCHIVED</h1>
...
</div>
Or if you think that is too cheap, declare two routes. The whole "create a whole new url path" is not as painful as you might think. It'll be considerably less complex than trying to wedge out a value from a route before it has loaded.
1: Try this. send json.status in $stateParams and apply condition inside stateProvider :
$stateProvider.state('home', {
templateProvider: ['$stateParams', 'restService' , function ($stateParams, restService) {
restService.getJson().then(function(json) {
if (status.status == 'archived') {
return '<div ng-include="first.html"></div>';
} else {
return '<div ng-include="second.html"></div>';
}
})
}]
});
2 : or simply in view you can try this:
<div ng-if="json.status == 'archived'">
<h1>ARCHIVED</h1>
...
</div>
<div ng-if="json.status != 'archived'">
<h1>NOT ARCHIVED</h1>
...
</div>

How do I format my AngularJS data model?

Hi I am just beginning with angular and I am struggling to find the answer to what I'm sure is quite a simple thing to do.
I am currently getting the values of some input boxes and pushing them into my scope. This is creating one long 'array' eg:
['data-1','data-2','data-3']
I would like to format my data in the following way instead
$scope.data = [
{
'header1': 'data1-1',
'header1': 'data1-2',
'header1': 'data1-3'
},
{
'header1': 'data2-1',
'header1': 'data2-2',
'header1': 'data2-3'
}
]
This is my function as it currently is.
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
$scope.td.push($(value).val());
});
}
Any help or pointers would be greatly appreciated as I am just getting my head round the angular way
Doing this isn't hard... but before I give you a gun to shoot yourself in the foot, just to say that I think it would be beneficial to explain WHY you want structure in that other format you are mentioning. You seem to have lots of data repetition and that's always a red flag.
Now for the code, you just need to create object before pushing it to the array like:
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
var obj = {
"header1": val + "-1",
"header2": val + "-2"
};
$scope.td.push(obj);
});
}
EDIT:
OK, so you are trying to add new row to the table. First of all, you shouldn't be doing angular.forEach, but rather those input elements in HTML should bind to existing scope object, like:
// obviously use better names than Input1Value
// I am here just giving you example
$scope.bindData = {
Input1Value: null,
Input2Value: null
};
// in HTML you will do
// <input ng-model="bindData.Input1Value" />
// <input ng-model="bindData.Input2Value" />
Now that you've eliminated that nasty angular.forEach you need to have some kind of event handler, for example when user clicks the button you want to add this object to the array to which table is data bound. Just be sure to clone the $scope.bindData object when you add it to array.
$scope.createRow = function(){
var newRowData = $scope.cloneObject($scope.bindData);
$scope.td.push(newRowData);
}
// http://heyjavascript.com/4-creative-ways-to-clone-objects/
// https://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
$scope.cloneObject = function(objToClone) {
var newObj = (JSON.parse(JSON.stringify(objToClone)));
}
To close this answer off - keep in mind, if you ever find yourself directly referencing HTML DOM elements in Javascript with AngularJS - you are doing something wrong. It's a nasty habit to eliminate, especially if you are coming from jQuery background (and how doesn't?), where everything is $("#OhHiThere_ElementWithThisId).
Obviously the main thread on this topic on StackOverflow is this one:
“Thinking in AngularJS” if I have a jQuery background?
However I find that it's too theoretical, so Google around and you may find better overviews like:
jQuery vs. AngularJS: A Comparison and Migration Walkthrough

Initiate D3.js data map with new data

I'm going with the basic example in here except I need to be able to update the map based on new data (a json file.) I couldn't find a way to load the data directly inside Datamap object, so I'm loading it with D3.json and using the command to update the map. For some reason the popupTemplate function is receiving null data object and I don't know how to fix it.
What's the best way to do this?
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.world.min.js"></script>
<script src="http://datamaps.github.io/scripts/topojson.js"></script>
<div id="container" style="position: relative; width: 500px; height: 300px;"></div>
<script>
var data;
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: '#FFFFFF',
defaultFill: 'green'
},
geographyConfig: {
popupTemplate: function(geo, data) {
console.log(data)
return ['<div class="hoverinfo"><strong>',
'Number of things in ' + geo.properties.name,
': ' + data[geo.id].numberOfThings,
'</strong></div>'].join('');
}
}
});
map.legend();
d3.json("path/to/data.json", function(error, json) {
if (error) return console.warn(error);
data = json;
map.updateChoropleth(data);
});
</script>
This is my json file:
{
"IRL": {
"fillKey": "LOW",
"numberOfThings": "2002"
},
"USA": {
"fillKey": "MEDIUM",
"numberOfThings": "10381"
}
}
To make it easier to debug, I put on jsfiddle
I did not have problems loading the data directly inside Datamap. In any case, I also simulated a data update...the color gets updated but not the value (numberOfThings). In the example in the tutorial, it is not clear this can be done although it would make sense that one should be able to update values.
I am leaving you with the FIDDLE showing the results of my experiment.
A couple of notes:
I believe your popup was not showing because its return string needs
to be data.numberOfThings.
If I am not mistaken when I played with this before, if you don't have data for a country, then the popup is not updated and the same value as for the last country with data is displayed.
#Kiarash, there are two problems here:
You are using the Datamaps from the datamaps.github.io site, which I don't recommend since I can't guarantee reliability (uptime) or backwards compatibility. You are best off downloading it from the Github project page
data won't have a property with the country name, it should be accessed like data.numberOfThings.
Here is a working version of the code you supplied

Load a single record from a JSON API using Sencha Touch 2

I am having a horrible time understanding Sencha Touch 2's architecture. I'm finding even the most basic things I do in other language and frameworks to be incredibly painful.
Currently, I just want to do a standard Master/Detail view. I load a store into a list view and would like to click on each list item to slide in a detail view. Since my initial list view can contain quite a lot of items, I'm only loading a little bit of the data with this method in my controller:
viewUserCommand: function(list, record) {
// console.log(record);
var profileStore = Ext.getStore("Profiles");
profileStore.setProxy({
url: 'http://localhost:8000/profile/' + record.data.user_id
});
profileStore.load();
// console.log(profileStore);
Ext.Viewport.animateActiveItem(Ext.getCmp('profileview'), this.slideLeftTransition);
}
First, modifying the url property for each tap event seems a bit hacky. Isn't there a way to specify "this.id" or something along those lines, and then pass that to my store? Or would that require loading the entire DB table into an object?
I can console.log the return from this method and it's exactly what I want. How do I populate the detail view? I've tried utilizing a DataView component, but it doesn't show any data. The examples on sencha's website are fairly sparse, and relatively contextless. That means that even copying and pasting their examples are likely to fail. (Any examples I've tried using Ext.modelMgr.getModel() have failed.)
I know it's partly that this framework is new and I'm probably missing a huge gaping hole in my understanding of it, but does anyone have any clue?
Would suggest you check out the docs, there's an example of loading a single model:
http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Model
Ext.define('User', {
extend: 'Ext.data.Model',
config: {
fields: ['id', 'name', 'email'],
proxy: {
type: 'rest',
url : '/users'
}
}
});
//get a reference to the User model class
var User = Ext.ModelManager.getModel('User');
//Uses the configured RestProxy to make a GET request to /users/123
User.load(123, {
success: function(user) {
console.log(user.getId()); //logs 123
}
});