Making a JSON Object as Google Maps API Call in React Native - google-maps

I wanted to call GoogleMapsAPI and get results with specified origin and destination. However, I cannot pass the result of the api call immediately because it returns the result after I do assign operation. I wanted to pass the result immediately but I couldn't find any proper solution. Here is my fetch code for API.
class RouteSelection extends Component {
constructor(props) {
super(props);
this.fetchApi = this.fetchApi.bind(this);
this.fetchDef = this.fetchDef.bind(this);
this.fetchFewer = this.fetchFewer.bind(this);
this.fetchLess = this.fetchLess.bind(this);
this.fetchBestGuessTraffic = this.fetchBestGuessTraffic.bind(this);
this.fetchPessimisticTraffic = this.fetchPessimisticTraffic.bind(this);
this.fetchOptimisticTraffic = this.fetchOptimisticTraffic.bind(this);
this.calcRoutes = this.calcRoutes.bind(this);
this.state = {
origin: "",
destination: "",
arrival_time: "",
def_data: [],
f_data: [],
l_data: [],
best_guess: [],
pessimistic_guess: [],
optimistic_guess: [],
};
}
fetchDef(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ def_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchLess(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=less_walking", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ l_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchFewer(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=fewer_transfers", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ f_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchBestGuessTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=best_guess", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ best_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchPessimisticTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=pessimistic", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ pessimistic_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchOptimisticTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=optimistic", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ optimistic_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchApi() {
this.fetchFewer();
this.fetchLess();
this.fetchDef();
this.fetchBestGuessTraffic();
this.fetchOptimisticTraffic();
this.fetchPessimisticTraffic();
}
calcRoutes(){
console.log("Fewer Transfers ");
console.log(this.state.f_data);
console.log("Less Walking ");
console.log(this.state.l_data);
console.log("Default ");
console.log(this.state.def_data);
console.log("Best Guess Traffic ");
console.log(this.state.best_guess);
console.log("Optimistic Guess Traffic ");
console.log(this.state.optimistic_guess);
console.log("Pessimistic Guess Traffic ");
console.log(this.state.pessimistic_guess);
this.props.navigator.push({
id: 'UserPref',
name: 'UserPref',
});
}

The above code implies that there are many asynchronous calls. In order to get defined values in logs you need to implement either async/await , callback or .then() i.e resolve promise.
we will implement callback in the above code snippet:-
I will do one for you and rest is for practice...
wherever you are calling onPress={() => this.fetchApi(function(data){calcRoutes(data)}) } just pass a callback..and instead of calling calcRoutes() function from different method call it here because you don't know when will response come.
After that :
fetchApi(callback) {
this.fetchFewer(function(data){callback(data)});
}
fetchFewer(callback){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=fewer_transfers", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => {this.setState({ f_data: responseData.routes }) callback(responseData.routes)})
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
This is how callback works...
Cheers :)

Related

Chrome DevTools Protocol - devtool can not get log info, when backend emit "Runtime.consoleAPICalled" event

I am writing a cdp backend for the chrome-devtool-frontend。
I can not see any output in chrome-devtool-frontend,when cdp backend emit "Runtime.consoleAPICalled" Event。
I make sure that I enable Runtime domain firstly.
"Runtime.executionContextCreated" event has been also emitted.
My cdp backend code:
const WebSocket = require('ws');
const executionContext = {
id: 1,
origin: 'http://my.local.xxxx.net:3000',
name: 'top',
};
(async () => {
const ws = new WebSocket(
'wss://xxxxxxxxx',
{ perMessageDeflate: false }
);
await new Promise((resolve) => ws.once('open', resolve));
console.log('connected!');
ws.on('message', (msg) => {
console.log(`Received: ${msg}`);
const messageObj = JSON.parse(msg);
const { id, method } = messageObj;
if (method === 'Log.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
}
if (method === 'Debugger.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {
debuggerId: '-252419454342719044.-5817058166285735043',
},
})
);
}
if (method === 'Runtime.runIfWaitingForDebugger' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
}
if (method === 'Runtime.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
ws.send(
JSON.stringify({
method: 'Runtime.executionContextCreated',
params: {
context: executionContext,
},
})
);
setTimeout(() => {
ws.send(
JSON.stringify({
method: 'Runtime.consoleAPICalled',
params: {
type: 'log',
args: [
{
type: 'string',
value: 'log here',
},
],
stackTrace: { callFrames: [] },
executionContextId: 1,
timestamp: new Date().getTime(),
},
})
);
}, 3000);
}
});
})();
Here is devtool's Protocal monitor screenshot

Get TypeError Network Request Failed using react native fetch json url

I would like to create simple apps that make user can post data to json.
Here is my code.
componentDidMount = () => {
fetch('https://site.json',
{
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example'
})
}
).then(response => response.json()).then(data => console.log(data))
.catch(err => console.log("api Erorr: ", err));
}
But finally, I get an error api Erorr: [TypeError: Network request failed]
Is it Cors block my access???
Any idea how to solve it, Thank you very much
There is something wrong with the URL. The same code working fine with other urls like.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example',
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log('api Erorr: ', err));
}}

SyntaxError: Unexpected token B in JSON at position 0 - JSON Rest API

I'm working with a JSON rest API that has the following response:
// response
[
{
id: 1,
userId: 1,
start: "2018-01-01 10:15",
finish: "2018-01-01 12:20",
breakLength: 30
},
{
id: 2,
userId: 1,
start: "2018-01-02 10:15",
finish: "2018-01-02 18:20",
breakLength: 45
}
];
See below for code. Like my other functions, I am requesting a GET using fetch(). However, sometimes this function when called requests and responds with a 200, and sometimes it responds with a 400 bad request(Uncaught (in promise) SyntaxError: Unexpected token B in JSON at position 0) It seems very random when it happens. My server which the JSON Rest API is on is localhost:3000 and my application is on localhost:3001. I have used this same method for other JSON requests and they work perfectly. I am not sure why this one is having trouble? Thanks for your help!
Update: It seems as though the last Promise.all, setState is not being executed. The program is crashing on line .then(response => response.json()) in promise3.
Updated Code:
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
callbackSessionId = (sessionId) => {
let promise1 = this.fetchUserAttributes(sessionId)
.then(response => response.json())
.then(json => this.setState({
userAttributes: json
}));
Promise.all([promise1]).then(() => {
let promise2 = this.getOrganisations(sessionId)
.then(response => response.json())
.then(json => this.setState({
organisations: json
}));
let promise3 = this.getShifts(sessionId)
.then(response => response.json())
.then(json => this.setState({
shifts: json
}));
// this.setState({
// sessionId: sessionId
// });
Promise.all([promise2, promise3]).then(() => {
this.setState({
sessionId: sessionId
});
});
});
};
Your JSON is actually invalid. All keys need to be string literals, so your correct JSON would look like this:
[
{
"id": 1,
"userId": 1,
"start": "2018-01-01 10:15",
"finish": "2018-01-01 12:20",
"breakLength": 30
},
{
"id": 2,
"userId": 1,
"start": "2018-01-02 10:15",
"finish": "2018-01-02 18:20",
"breakLength": 45
}
]
There are a few issues in your code: you should always return your promises, headers property names should be quoted and React setState is an asynchronous method.
Please, try to update it like below to see if it works, I'll edit expanding on the details if it does.
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
fetchData = (sessionId) => {
let promise3 = this.getShifts(this.state.sessionId)
.then(response => response.json())
.then(json => this.setState({shifts: json}, this.forceUpdate));
};

How can i get response from fetch API React Native

{
"success":true,
"result":{
"sessionName":"2a7777703f6f219d"
"userId":"19x1"
"version":"0.22"
}
};
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
How can i get response from fetch API React Native (Post method)
I need to console.log to see sessionName in result (I think it's response.result.sessionName)
But I don't know how to get it from fetch.
Where is response from fetch like a get method
Here's Get method from facebook (it's have response)
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
You can just do the same as GET method:
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);// your JSON response is here
})
.catch((error) => {
console.log(error);
});

Extract data from JSON list in React native

I want to parse a JSON file and display some data on the screen. I am able to display all the data using the following code, but I want to display only entryDate and sysol. Is it possible to use a for loop in _onPressButtonGET() and display data there only?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
TouchableHighlight,
Alert,
TextInput
} from 'react-native';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import Home from './Home'
export class Temp extends Component{
constructor(props) {
super(props);
this.state = {
data: '',
data1:'',
textinput:'',
entryDate:[]
}
state={
shouldShow: false
}
}
componentDidMount(){
this._onPressButtonGET();
}
_onPressButtonPOST(){
fetch(URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"entryDate":"3/2/2017 2:00 AM",
"systol": this.state.textinput,
"mobileType":"ANDROID",
"userName":"menutest",
})})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"Blood pressure data",
"Blood pressure data - " + JSON.stringify(responseData)
)
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
}
_onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
.then((response) => response.json())
.then((responseData) => {
this.setState({ data : JSON.stringify(responseData) })
data["list"].map(d => this.state.entryDate.push(d.entryDate));
this.setState({ entryDate: jsonResponse.entryDate, systol: responseData.systol })
}).catch((error) => {
Alert.alert('problem while getting data');
})
.done();
}
render(){
return(
<View>
<TouchableHighlight onPress={this._onPressButtonPOST.bind(this)}>
<Text>Add</Text>
</TouchableHighlight>
<TouchableOpacity style= {{left:300,top:-20, }}
onPress={()=>{ this.setState({ shouldShow: !this.state.shouldShow })}}
><Text>Edit</Text></TouchableOpacity>
{this.state.shouldShow ? <TextInput placeholder='systol'
onChangeText={(text) => this.setState({textinput: text})}
/> : null}
<TouchableHighlight onPress={this._onPressButtonGET.bind(this)}>
<Text>show</Text>
</TouchableHighlight>
this.state.entryDate.map( d => (<Text>{d}</Text>));
<Text>{this.state.entryDate}</Text> //not displaying anythong
<Text>{this.state.data && JSON.parse(this.state.data)['entryDate']}</Text> //not displaying anything
<Text>hello{this.state.data}</Text> //printing all data
</View>
);
}
}
module.exports = Temp;
JSON:
{
"List": [
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
}
]
}
first initialize entryData as array
this.state = {
entryDate: [],
}
in _onPressButtonGET() use
data["List"].map(d => this.state.entryData.push(d.entryDate));
in render use map to display all data like that
this.state.entryDate.map( d => (<Text>{d}</Text>));
onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
}
.then(response => {
this.setState({entryDate:response.data})
});
renderEntryDate() {
this.state.entryDate.map((item)=>{
<Text>{item.entryDate}</Text>
})
}
render() {
return (
<View>
<Button style= {{
backgroundColor: '#6656B4',
width: 200,
height: 40,
}
onPress={() => this.onPressButtonGET()}
title="Get Weather"
color="#841584"
/>
{this.renderEntryDate()}
<View>
);
}