I am new in react native and I need to take information from JSON file asynchronously on change text in input field.
JSON:
{ "meta": {
"code": 200,
"api_version": "2.0.1.6.0",
"issue_date": "20160620"
},
"result": {
"total": 4,
"items": [{
"purpose_name": "Торгово-развлекательный комплекс",
"name": "Asia Park, торгово-развлекательный комплекс",
"full_name": "Алматы, Asia Park, торгово-развлекательный комплекс",
"id": "9430047374983999",
"building_name": "Asia Park, торгово-развлекательный комплекс",
"address_name": "Райымбека проспект, 514а / Саина, 516",
"type": "building"
}]
}
}
If it is a local JSON file you can just use require:
const data = require('./data.json');
console.log( data.result.items[0].purpose_name );
If it is a remote API request try fetch:
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log( data.result.items[0].purpose_name ))
.catch(error => console.log(error));
If this file is local you may simply require it, it will get parsed automatically. If it is on some server you need to use the Fetch API.
Related
I am doing a contacts app using expo-contacts, I can see contacts but the problem comes when I need to add one.
This is the code I am using, the thing is that in some phones works and in other doesn't. Just to let you know, the permissions to write and read are already attached in app.json.
<Button
title="Guardar"
onPress={async () => {
const contact = {
[Contacts.Fields.FirstName]: "Test",
[Contacts.Fields.LastName]: "McTest",
[Contacts.Fields.PhoneNumbers]: [
{
number: "(123) 456-7890",
isPrimary: true,
digits: "1234567890",
countryCode: "PA",
id: "1",
label: "main",
},
],
[Contacts.Fields.Emails]: [
{
email: "test#gmail.com",
isPrimary: true,
id: "2",
label: "main",
},
],
};
await Contacts.addContactAsync(contact)
.then((contactId) => {
alert("Se creó exitosamente");
})
.catch((err) => {
alert(err);
console.log(err);
});
}}
The error I am getting is this: Error: insert into content://com.android.contacts/data returned no result.
To finish its important to say that I am using apk already built and not doing in debugging mode in expo.
I will appreciate your answers.
Solved: it was how i organiced data structure to push contact details.
[Contacts.Fields.PhoneNumbers]: [
{
number: "(123) 456-7890",
isPrimary: true,
digits: "1234567890",
countryCode: "PA",
id: "1",
label: "main",
},
]
Changing label from 'main' to 'mobile' worked for me.
Hi i have self hosted parse server on digital ocean, it is sending notifications on iOS but not on android. my index.js file looks like this:
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://1.1.1.1"1/app_name',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: 'abc',
masterKey: 'def',
serverURL: 'http://1.1.1.1:1337/parse' || 'http://localhost:1337/parse',
verbose: true,
push: {
android:{
senderId: 'my FCM id',
apiKey: 'my FCM key'
},
ios: {
pfx: '1',
bundleId: '2',
production: true
}
}
});
when i send a push from the parse dashboard (also self hosted), this is the response i get with verbose:true:
"results": [
{
"objectId": "bNtZqwY8",
"pushTime": "2017-06-13T10:49:06.095Z",
"query": "{\"UniqueId\":\"c49de788ce\",\"deviceType\":{\"$in\":[\"android\"]}}",
"payload": "{\"alert\":\"Thank you for using my app.\"}",
"source": "rest",
"status": "succeeded",
"numSent": 0,
"pushHash": "266b6b637152b36040830",
"createdAt": "2017-06-13T10:49:06.095Z",
"updatedAt": "2017-06-13T10:49:06.214Z",
"numFailed": 15,
"failedPerType": {
"android": 15
},
"ACL": {}
},
{
"objectId": "rsYinvGG",
"pushTime": "2017-06-13T10:48:42.449Z",
"query": "{\"UniqueId\":\"7A0A-9AEA-5870FDEC42A3\"}",
"payload": "{\"alert\":\"one\",\"link_key\":1,\"sound\":\"default\"}",
"source": "rest",
"status": "succeeded",
"numSent": 2,
"pushHash": "246431e019c0357dcb180c7",
"createdAt": "2017-06-13T10:48:42.449Z",
"updatedAt": "2017-06-13T10:48:43.282Z",
"numFailed": 0,
"sentPerType": {
"ios": 2
},
"ACL": {}
},
When i send push on android from FCM, it works. Im really lost here with android push, can someone please point me in the right direction.
Here is the output from the log:
ESC[36mverboseESC[39m: REQUEST for [PUT] /parse/classes/_Installation /zKIp8LLOWr: {
"GCMSenderId":"diMV6Hm3j07dbqVPEsZRgqNzDo3YvA5zNdUmtO6Q4ka5ijRyyIRHiWCWOBVBDA22OIls-4bO06kxDPuOKFwJUZuMD3Xt41WuKUoOJwBlW7cKdqv9llj7Me0uiWFLWDwS7V",
"UniqueId": "a59020fff8ca30d00",
"appVersion": "2.3.3",
"objectId": "zKIp8LLOWr"
} method=PUT, url=/parse/classes/_Installation/zKIp8LLOWr, x-parse- app-display-version=2.3.3, x-parse-installation-id=29918e2f-8bbd-4ab7-975f-f854e1f43689, user-agent=Parse Android SDK 1.13.1 (com.mrfizzy/18) API Level 21, connection=Keep-Alive, accept-encoding=gzip, x-parse-os-version=5.0, x-parse-app-build-version=18, content-type=application/json, x-parse-client-key=, x-parse-client-version=a1.13.1, host=46.101.199.219:1337, content-length=245, x-parse-application-id=JHyfl9YhXCQ24r6J8ohdVlHLt1hfWhB4MF2jQAQn, GCMSenderId=diMV6HmLH3I:APA91bFQS4Sq9G5wlej07dbqVPEsZRgqNzDo3YvA5zNdUmtO6Q4ka5ijRyyIRHiWCWOBVBDA22OIls-4bO06kxDPuOKFwJUZuMD3Xt41WuKUoOJwBlW7cKdqv9llj7Me0uiWFLWDwS7V, UniqueId=a59020a48ca30d00, appVersion=2.3.3, objectId=zKIp8LLOWr
ESC[31merrorESC[39m: Error generating response. ParseError { code: 101, message: 'Object not found for update.' } code=101, message=Object not found for update.
[object Object]
It appears you're not assigning the Sender Id properly. You're passing an objectId that doesn't seem to be correct. Make sure you use ParseInstallation.getCurrentInstallation() when you set your GCM sender id rather than trying to get the installation by any other means.
http://parseplatform.org/Parse-SDK-Android/api/com/parse/ParseInstallation.html#getCurrentInstallation()
Hey guys i am trying to fetch data from remote server and returning in alertbox using react-native
Here's my code for fetching
_onPressButtonPOST: function(){
fetch("http://www.example.com/endpoint", {
method: "POST",
body: JSON.stringify({
key: "value",
})
})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData.body)
)
})
.done();
},
Here is what i want to fetch from my endpoints.
{
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "service",
"_type": "service",
"_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"_score": 1,
"_source": {
"service_owner_id": "2",
"service_name": "miamia",
"service_email": "mk#gmail.com",
"service_contact_name": "mukesh",
"service_landline_number": "12345",
"service_mobile_number": "1234567890",
"service_address": "vdvml",
"service_listingType": 1,
"service_avg_rating": 3.5,
"sarvice_ratingcount": 10,
"service_serviceType": 1,
"service_working_hour": [
""
],
"service_subcat_ids": "2,3",
"service_description": "hi I am mukesh kumar ",
"service_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"service_logo_url": "",
"service_gallery_url": "",
"service_location": {
"lat": 19.34,
"lon": 72.845
},
"service_subcategory": "CAT GER ",
"service_review": []
}
}
]
},
"took": 2,
"timed_out": false
}
But in alertbox it is showing undefined what might be the issue? can anyone help on this?
Thanks in advance.
Hey guys i found out the bug and consumed the API successfully thanks to https://www.thepolyglotdeveloper.com/2015/09/make-http-requests-in-ios-with-react-native/
I just replaced responseData.body with responseData as there was no body included in my server side code so it was returning undefined
Here is my sample code
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
})
.done();
Any doubts and queries are welcome.
Generally another reason is that, in PHP endpoint code they try to fetch the parameters sent by using $_POST, $_GET or $_REQUEST.
In that case, instead of Json, use FormData as body's value in your fetch operation.
An example
var FormDataToPost = new FormData();
FormDataToPost.append('userId', 12);
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: FormDataToPost
})
.then((response) => response.json())
.then((responseData) => { do something })
.catch((error) => {
alert(error);
})
.done();
I have a json Output from fetch method, which is something like in this format
{
"example": {
"id": "301",
"example_n": "example",
"exampleid": "12",
"thumbnail": "some url",
"examplearry": [
{
"example_id": "9",
"exampletitle": "exampletitle ",
},
{
"example_id": "10",
"exampletitle": "exampletitle",
},
{
"example_id": "7",
"exampletitle": "exampletitle",
}, "example_api": "6vvdncv99hbnbscm"
}
Now i want to access example_id and exampletitle. How to use it in react native?
You can see how to do it here.
Implement something like the fetchData method they have:
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
examplearry: responseData.examplearry,
});
})
.done();
}
This will process your json response and then, with this.setState, you can make your data available. After this, just access the examplearry like you would in javascript/react. The tutorial also shows how to do this in detail in the next step.
I have an url,get and response given. I have to parse the JSON and show the locations in Map in android. I dont need you to code. I am new in JSON. please tell me some steps how i can do that. how should i start and which steps i should take?
Url: "Some url"
Sending data:
{
"tag": "getAvailableDriver",
"lat": 41.022348,
"lng": -91.966721
}
RESPONSE:
{
"posts": [
{
"success": "1",
"driver": [
{
"id": "768",
"lat": "41.022848",
"lon": "-91.966884",
"recorded_datetime": "2014-07-20 20:18:03",
"user_id": "403",
"cabbi_state": "OnJob",
"vehicleType": "Black Cab",
"driver_name": "black cab driver",
"pic_name": "userimage/403.jpg",
"rating": "0",
"car_model": "this",
"number_sit": "4",
"distance": 0.035574527536789
}
],
"operator": [],
"nearestdistance": [
{
"distance": 0.03541809,
"time": 5
}
],
"car_models": [
"Taxi"
]
}
]
}
I just want anyone of you to guide me or show me the way. And also please someone tell me what will be the use of "send data" here. What is the use? I promise i will not ask any basic questions after i catch the grip. Help me please.
You can save the parsed data in an array, and for what I can see, there's a lot of tags in the JSON object. I suggest you to create an object of the type "Driver" or "Car", and then save all the data in that object. Once you have the data parsed and saved in an Array of the type of your object (Let's say an array of "Drivers" then you can use the info to add it into the Map.