Wasteland Wasteland - 2 months ago 21
React JSX Question

Javascript - extract data from object

Hi I'm trying to extract some data from an object (through a web API) in ReactJS (but I guess the question is not react specific). I think what API returns is not a properly constructed JS object.

You can see it in the browser:
https://poloniex.com/public?command=returnTicker

How do I map it to a proper object in JS.

Here's my code:

import React, { Component } from 'react';
import Place_holder from './place_holder';

const ticker = "https://poloniex.com/public?command=returnTicker";



class Body extends Component {
constructor(props) {
super(props);
this.state = { value: ""};
}


handleChange(value) {
this.setState({value});
}

getTicker(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send();

let tick = xhr.responseText;
console.log(tick.type);
return tick;
}



render() {
return (
<div>
<p>{this.getTicker(ticker)}</p>
<input
type="number"
value={this.state.value}
onChange={event => this.handleChange(event.target.value)}
/>

<Place_holder num={this.state.value} />
</div>
)
}
}

export default Body;


This prints the whole object. I can't seem to be able to extract info from it.

EDIT:
I've added the JSON.parse bit and now I get the following error:

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {BTC_1CR, BTC_BBR, BTC_BCN, BTC_BELA, BTC_BITS, BTC_BLK, BTC_BLOCK, BTC_BTCD, BTC_BTM, BTC_BTS, BTC_BURST, BTC_C2, BTC_CGA, BTC_CLAM, BTC_CURE, BTC_DASH, BTC_DGB, BTC_DIEM, BTC_DOGE, BTC_EMC2, BTC_FLDC, BTC_FLO, BTC_GEO, BTC_GAME, BTC_GRC, BTC_HUC, BTC_HZ, BTC_LTBC, BTC_LTC, BTC_MAID, BTC_MMNXT, BTC_OMNI, BTC_MYR, BTC_NAUT, BTC_NAV, BTC_NBT, BTC_NEOS, BTC_NMC, BTC_NOBL, BTC_NOTE, BTC_NSR, BTC_NXT, BTC_PINK, BTC_POT, BTC_PPC, BTC_QBK, BTC_QORA, BTC_QTL, BTC_RBY, BTC_RDD, BTC_RIC, BTC_SDC, BTC_SJCX, BTC_STR, BTC_SYNC, BTC_SYS, BTC_UNITY, BTC_VIA, BTC_XVC, BTC_VRC, BTC_VTC, BTC_XBC, BTC_XCN, BTC_XCP, BTC_XDN, BTC_XEM, BTC_XMG, BTC_XMR, BTC_XPM, BTC_XRP, BTC_XST, USDT_BTC, USDT_DASH, USDT_LTC, USDT_NXT, USDT_STR, USDT_XMR, USDT_XRP, XMR_BBR, XMR_BCN, XMR_BLK, XMR_BTCD, XMR_DASH, XMR_DIEM, XMR_LTC, XMR_MAID, XMR_NXT, XMR_QORA, XMR_XDN, BTC_IOC, BTC_ETH, USDT_ETH, BTC_SC, BTC_BCY, BTC_EXP, BTC_FCT, BTC_BITCNY, BTC_RADS, BTC_AMP, BTC_VOX, BTC_DCR, BTC_LSK, ETH_LSK, BTC_LBC, BTC_STEEM, ETH_STEEM, BTC_SBD, BTC_ETC, ETH_ETC, USDT_ETC}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Body`.

Answer

The API is returning a JSON string. There are bunches of ways to deal with this, but in the context of your code, you might just want to use:

var tickdata = JSON.parse(xhr.responseText);

See example.