how to access obj from json in React? - javascript

Api Respose :-
[
{
"System Name": "Name1",
"Primary Sensor": "WWWW",
"Mean Wind Speed": "6.23 m/s",
"Status": 1,
"mws_number": 44,
"DRR (%)": "100",
"drr_number": 100
},
{
"System Name": "Name 2",
"Primary Sensor": "SSSS",
"Mean Wind Speed": "4.2 m/s",
"Status": 2,
"mws_number": 6,
"DRR (%)": "100",
"drr_number": 100
}
]
My Code ->
class Home extends Component {
state = {
items:[],
isLoading:false
}
componentDidMount() {
// api
fetch('http://api.url', {
method: 'POST',
body:
JSON.stringify({"Authentication":'token'})
}).then(data => data.json() )
.then(res =>{
this.setState({isLoading:true,
items:res,}
)
});
}
render() {
return (
<>
{console.log(this.state.items[0])} // getting o/p - first obj of array
{console.log(this.state.items[0].Status)} // getting Error undef Status
{console.log(this.state.items.Status[0])} // same error undef status
</>
)
export def ....
This is my complete piece of code... I can't add api url as it is not public api :(
I want to access this data inside of the array =>(Status, System Name, etc)
how can i fetch this !!

Here, console.log(this.state.items[0]); is getting called two times;
- When the page first loads and API request is not finished.
- After the API request finishes and you call this.setState
Solution would be to check that items' length is greater than 0 before trying to use it. Try changing console.log(this.state.items[0]); to this:
if (this.state.items.length > 0) { console.log(this.state.items[0].Status); }

I would suggest you to use componentWillMount() instead of componentDidMount() becuase componentWillMount() happens before render while componentDidMount() happens after the first render.May be that help.

Related

React PayPal Checkout

I built a small and simple webshop with a PayPal checkout and it works so far. Know I want to see in the transaction history of my PayPal account the product which was purchased. So I need to add more details about the purchase to see what order was placed.
I found multiple tutorials but I still don't know how to implement this. This is my payPalButton component so far:
How can I add more details to the payment object??
import React from 'react';
import PaypalExpressBtn from 'react-paypal-express-checkout';
export default class MyApp extends React.Component {
render() {
const onSuccess = (payment) => {
payment.console // Congratulation, it came here means everything's fine!
.log('The payment was succeeded!', payment);
this.props.clearCart();
this.props.history.push('/');
// You can bind the "payment" object's value to your state or props or whatever here, please see below for sample returned data
};
const onCancel = (data) => {
// User pressed "cancel" or close Paypal's popup!
console.log('The payment was cancelled!', data);
// You can bind the "data" object's value to your state or props or whatever here, please see below for sample returned data
};
const onError = (err) => {
// The main Paypal's script cannot be loaded or somethings block the loading of that script!
console.log('Error!', err);
// Because the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js"
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear
};
let env = 'sandbox'; // you can set here to 'production' for production
let currency = 'EUR'; // or you can set this value from your props or state
// let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout
// Document on Paypal's currency code: https://developer.paypal.com/docs/classic/api/currency_codes/
const client = {
sandbox: process.env.REACT_APP_ID,
production: 'YOUR-PRODUCTION-APP-ID',
};
// In order to get production's app-ID, you will have to send your app to Paypal for approval first
// For sandbox app-ID (after logging into your developer account, please locate the "REST API apps" section, click "Create App"):
// => https://developer.paypal.com/docs/classic/lifecycle/sb_credentials/
// For production app-ID:
// => https://developer.paypal.com/docs/classic/lifecycle/goingLive/
// NB. You can also have many Paypal express checkout buttons on page, just pass in the correct amount and they will work!
return (
<PaypalExpressBtn
env={env}
client={client}
currency={currency}
total={this.props.total}
onError={onError}
onSuccess={onSuccess}
onCancel={onCancel}
style={{
size: 'small',
color: 'blue',
shape: 'rect',
}}
/>
);
}
}
You may be using an older react component, try https://www.npmjs.com/package/react-paypal-button-v2
Don't use onSuccess, switch to onApprove: https://stackoverflow.com/a/62193541/2069605
Here is an example of a v2/orders purchase_units object with a description and two items:
"purchase_units": [{
"description": "Stuff",
"amount": {
"value": "20.00",
"currency_code": "USD",
"breakdown": {
"item_total": {
"currency_code": "USD",
"value": "20.00"
},
}
},
"items": [
{
"unit_amount": {
"currency_code": "USD",
"value": "10.00"
},
"quantity": "1",
"name": "Item 1",
},
{
"unit_amount": {
"currency_code": "USD",
"value": "10.00"
},
"quantity": "1",
"name": "Item 2",
},
],
}]
(A lot of those fields are actually required and the totals must match up, so it's very useful to have this sample as a starting point.)

Dialogflow Fulfilment webhook call failed

I am new to dialogflow fulfillment and I am trying to retrieve news from news API based on user questions. I followed documentation provided by news API, but I am not able to catch any responses from the search results, when I run the function in console it is not errors. I changed the code and it looks like now it is reaching to the newsapi endpoint but it is not fetching any results. I am utilizing https://newsapi.org/docs/client-libraries/node-js to make a request to search everything about the topic. when I diagnoise the function it says " Webhook call failed. Error: UNAVAILABLE. "
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const http = require('http');
const host = 'newsapi.org';
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('63756dc5caca424fb3d0343406295021');
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) =>
{
// Get the city
let search = req.body.queryResult.parameters['search'];// search is a required param
// Call the weather API
callNewsApi(search).then((response) => {
res.json({ 'fulfillmentText': response }); // Return the results of the news API to Dialogflow
}).catch((xx) => {
console.error(xx);
res.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
});
});
function callNewsApi(search)
{
console.log(search);
newsapi.v2.everything
(
{
q: 'search',
langauge: 'en',
sortBy: 'relevancy',
source: 'cbc-news',
domains: 'cbc.ca',
from: '2019-12-31',
to: '2020-12-12',
page: 2
}
).then (response => {console.log(response);
{
let articles = response['data']['articles'][0];
// Create response
let responce = `Current news in the $search with following title is ${articles['titile']} which says that
${articles['description']}`;
// Resolve the promise with the output text
console.log(output);
}
});
}
Also here is RAW API response
{
"responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
"queryResult": {
"queryText": "what is the latest news about toronto",
"parameters": {
"search": [
"toronto"
]
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
""
]
}
}
],
"intent": {
"name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
"displayName": "misty.news"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 543
},
"languageCode": "en"
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
},
"outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
"outputAudioConfig": {
"audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
"synthesizeSpeechConfig": {
"speakingRate": 1,
"voice": {}
}
}
}
And Here is fulfillment request:
{
"responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
"queryResult": {
"queryText": "what is the latest news about toronto",
"parameters": {
"search": [
"toronto"
]
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
""
]
}
}
],
"intent": {
"name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
"displayName": "misty.news"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 543
},
"languageCode": "en"
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
},
"outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
"outputAudioConfig": {
"audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
"synthesizeSpeechConfig": {
"speakingRate": 1,
"voice": {}
}
}
}
Also here is the screenshot from the firebase console.
Can anyone guide me what is that I am missing in here?
The key is the first three lines in the error message:
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'newsapi'
It is saying that the newsapi module couldn't be loaded and that the most likely cause of this is that you didn't list this as a dependency in your package.json file.
If you are using the Dialogflow Inline Editor, you need to select the package.json tab and add a line in the dependencies section.
Update
It isn't clear exactly when/where you're getting the "UNAVAILABLE" error, but one likely cause if you're using Dialogflow's Inline Editor is that it is using the Firebase "Spark" pricing plan, which has limitations on network calls outside Google's network.
You can upgrade to the Blaze plan, which does require a credit card on file, but does include the Spark plan's free tier, so you shouldn't incur any costs during light usage. This will allow for network calls.
Update based on TypeError: Cannot read property '0' of undefined
This indicates that either a property (or possibly an index of a property) is trying to reference against something that is undefined.
It isn't clear which line, exactly, this may be, but these lines all are suspicious:
let response = JSON.parse(body);
let source = response['data']['source'][0];
let id = response['data']['id'][0];
let name = response['data']['name'][0];
let author = response['author'][0];
let title = response['title'][0];
let description = response['description'][0];
since they are all referencing a property. I would check to see exactly what comes back and gets stored in response. For example, could it be that there is no "data" or "author" field in what is sent back?
Looking at https://newsapi.org/docs/endpoints/everything, it looks like none of these are fields, but that there is an articles property sent back which contains an array of articles. You may wish to index off that and get the attributes you want.
Update
It looks like that, although you are loading the parameter into a variable with this line
// Get the city and date from the request
let search = req.body.queryResult.parameters['search'];// city is a required param
You don't actually use the search variable anywhere. Instead, you seem to be passing a literal string "search" to your function with this line
callNewsApi('search').then((output) => {
which does a search for the word "search", I guess.
You indicated that "it goes to the catch portion", which indicates that something went wrong in the call. You don't show any logging in the catch portion, and it may be useful to log the exception that is thrown, so you know why it is going to the catch portion. Something like
}).catch((xx) => {
console.error(xx);
res.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
});
is normal, but since it looks like you're logging it in the .on('error') portion, showing that error might be useful.
The name of the intent and the variable I was using to make the call had a difference in Casing, I guess calls are case sensitive just be aware of that

React grabbing JSON response property

I'm very new to React. I have a JSON response that is being returned to me VIA WebAPI 2.
I would like to display only parts of this reply, for example if i only want to display the title
I have implemented the following code, but when view title it shows up as undefined
App.js
class App extends React.Component {
constructor(props){
super(props);
this.state = {reply: ""}
this.callAPI = this.callAPI.bind(this);
}
componentDidMount(){
this.callAPI();
}
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json();
}).then(responseData => {
this.setState({reply:responseData});
console.log("REPONSEDATA-----"+responseData);
console.log(responseData.title);
});
}
render(){
return(
<div>
</div>
);
}
}
Update 1
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(response =>{
return response.json().then(responseData => {
this.setState({reply:responseData});
console.log("RESPONSE----"+JSON.stringify(responseData));
console.log(responseData.title);
});
});
}
API JSON Response
[{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 1,
"externalId": null
},
"internalVersion": 2,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._Annual Returns_2012-01-03",
"extension": "pdf",
"logicalSize": "47872",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:41.510Z",
"lastAccessedAtUtc": "2019-07-10T21:00:28.029Z",
"lastWrittenAtUtc": "2019-05-27T15:17:48.000Z",
"changedAtUtc": "2019-05-27T15:17:48.000Z",
"fileGuid": "{881D8975-84B9-4A73-9AFF-F0C61C94FE90}",
"checksumMD5": "24f6badff8b70783697e0052fc4a7fe6",
"fileMissing": false,
"contentIsVolatile": false
}][{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 2,
"externalId": null
},
"internalVersion": 3,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._By-Law #1_",
"extension": "pdf",
"logicalSize": "951046",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:42.000Z",
"lastAccessedAtUtc": "2019-07-10T21:02:54.062Z",
"lastWrittenAtUtc": "2019-05-27T15:16:28.000Z",
"changedAtUtc": "2019-05-27T15:16:28.000Z",
"fileGuid": "{F8B54DB0-7E9F-4F0F-8ABA-D03C1DE4FF8C}",
"checksumMD5": "ffe728ef1a87f0cec7737b6d224bb50d",
"fileMissing": false,
"contentIsVolatile": false
}]
Not sure what im doing wrong here, ive used Ajax a lot so maybe im confusing what can be done with react and fetch
Update 2
So it seems that this may be a single object, and not an array of objects.
console.log("RESPONSE----"+JSON.stringify(responseData));
var arr = [];
console.log("KEYS"+Object.keys(responseData));
Object.keys(responseData).forEach(function(key){
console.log(responseData[key]);
arr.push(responseData[key]);
When i try to access responseData[key] i end up getting a single letter, and not a property from the json response
This pushes me to believe that this is not an array of objects but a single object
you should use JSON.stringify when printing full json response and if part of the object is string (eg... response.title then its ok but if not you can try .toString() or JSON.stringify)
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json().then((responseData)=>{
this.setState({reply:responseData});
console.log("REPONSEDATA----"+JSON.stringify(responseData));
console.log(responseData.title);
return responseData
});
}

Get request with fetch and react

This is probably a very dumb question, but I cant find any solution on the web, please dont bash me. I set up a create-react-app and want to display some data in a table.
This is my JSON:
[ {
"unitid" : 29,
"createddate" : 1510324778000,
"latitude" : 49.402008056640625,
"longitude" : 11.901968002319336,
"senderid" : 6,
"signalstrength" : 37
}, {
"unitid" : 34,
"createddate" : 1510563384000,
"latitude" : 49.22679901123047,
"longitude" : 12.845210075378418,
"senderid" : 8,
"signalstrength" : 0
},......
And my table needs a JSON Array with all the attributes in order to display every column correctly.
This is the code where I try to fetch the data from an endpoint of mine:
class App extends Component {
constructor(props){
super(props);
this.state = {
vehicleList: [],
};
}
componentDidMount(){
fetch('endpoint-link', {mode: 'no-cors', method: 'get'})
.then(response => response.json())
.then(result => {
this.setState({vehicleList: result.vehicleList})
console.log(result)
})
.catch(error => {
this.setState({isLoaded: true, error})
console.log(error)
});
}
render() {
const {vehicleList} = this.state;
console.log(vehicleList);.......
When I open the Devtools in Chrome, go for "Network" I can see that the endpoint is known and the data is found, but somehow the fetch method is not loading the JSON into the Array.
Your JSON doesn't have a vehicleList property. It just has the array of vehicles. So you need to put that in your state:
this.setState({vehicleList: result})
The problem is this -> ...{mode="no-cors"...}
See this post in order to fix it: Handle response - SyntaxError: Unexpected end of input

Operating on JSON returned from http.get in Angular 4.3

In my my, I am attempting to serve dynamic form controls via JSON to a form builder similar to the dynamic forms tutorial at angular.io. I am having trouble operating on JSON data returned from an http.get() request. I can console.log the whole object, but if I try to log a sub-object, I get "undefined" in the console.
Here is my component file:
export class TestComponent implements OnInit {
dataSource: Observable<any>;
questions: QuestionBase<any>[] = [];
results: QuestionBase<any>[] = [];
constructor(private http: HttpClient) {
this.dataSource = this.http.get('/questions');
}
ngOnInit() {
this.dataSource.subscribe(
data => {
this.results = data['contactInfo'];
console.log(this.results[0].controlType);
this.results.forEach((item: QuestionBase<any>) => {
if(item.controlType == 'text') {
console.log(item.controlType);
this.questions.push(new TextQuestion(item));
}
else if(item.controlType == 'dropdown') {
console.log(item.controlType);
this.questions.push(new DropdownQuestion(item));
}
});
console.log(this.questions);
},
err => {
console.log("Cannot get JSON data. Error Code: %s, URL: %s",
err.status, err.url)
},
() => console.log('Done')
);
}
}
In the data => {} callback, if I console.log(request), the console displays the entire object just fine. I can even read sub-objects in the template. But, if I try to console.log or do any other thing with sub-objects as in the code above, e.g. the forEach() method, I get "undefined" on the console. What am I doing wrong?
Edit: Here is the JSON snippet:
{
"contactInfo": [
{
"key": "firstName",
"globalLabel": "First Name",
"controlType": "text",
"required": "true",
"order": "1"
},
{
"key": "lastName",
"globalLabel": "Last Name",
"controlType": "text",
"required": "true",
"order": "2"
},
{
"key": "streetAddress",
"globalLabel": "Street Address",
"controlType": "text",
"required": "true",
"order": "3"
}, ...}]
Edit #2 I had failed to restart my Node server after updating the JSON file to read "controlType" over an earlier version that used simply "type." I figured the server would automatically serve the newly edited and saved file, but it seems as though one must restart the server in order to do this. ISSUE CLOSED

Categories

Resources