How to fetch data from API in react-native - android

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();

Related

React native android API call not happened one specific endpoint

hi I have one endpoint which is pass multipart formdata
URL : http://100.20.168.179/public/index.php/maintenances/create_ticket
Method: Post
Body request
const SelectData = {
"description": "Fff",
"room_id": "Ghh",
"maintenance_unique_id": "1662630778728",
"lang_flag": "en",
"asset_type": "2",
"longitude": "0.0",
"work_type": "69",
"user_id": "20",
"latitude": "0.0",
"area": "291",
"location": "22",
"urgency_level": "4",
"category_name": "",
"device_id": "2",
"captured_adress": "3377",
"reported_on": "2022-09-08 03:22:58",
"is_mediafile": "0"
}
My code as below
const form = new FormData();
const imageFileData = {
name: imageFilePath?.fileName,
type: `image/jpg`,
uri: imageFilePath?.uri,
};
form.append('webdata', JSON.stringify(SelectData));
if (imageFilePath?.uri || videoFilePath?.uri ) {
form.append('file_name', imageFileData );
}
else{
form.append('file_name', JSON.stringify(null));
}
addTicket(Config.BASE_URL + '/maintenances/create_ticket',form);
useAddTicket.ts
const useAddTicket = () => {
// const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const navigation = useNavigation();
const addTicket = async (url: string, data: any) => {
console.log('formDatain Hook', data);
console.log('url Hook', url);
console.log('internet', globals.GlobalVariable.isConnected);
if (globals.GlobalVariable.isConnected === true) {
try {
setIsLoading(true);
const headers = {
'Content-Type': 'multipart/form-data; boundary=V2ymHFg03ehbqgZCaKO6jy',
// Connection: 'keep-alive',
// 'Content-Disposition': 'form-data; name="webdata"',
};
const response = await axios.post(url, data, { headers: headers });
if (response.data.sStatus == 1) {
setIsLoading(false)
console.log('useAddTicket Data res -->', response);
Alert.alert(`${response.data.sData.maintenance_id}`, response.data.sMessage, [
{ text: 'OK', onPress: () => navigation.goBack() },
]);
}
} catch (error) {
console.log('useAddTicket error -->', error);
setIsLoading(false);
}
} else {
Alert.alert('No Internet!');
}
};
return {
isLoading,
// data,
addTicket,
};
};
export default useAddTicket;
Issue is Above code working in iOS emulator but in Android it is not working in emulator as well as Real device . When i try to run in android it is continuously loading API call is not happened so any idea how can I solve this ? Your all suggestions is appreciated
NOTE: I mage getting log till internet true inside addTicket function. It means my request is not reach to Endpoint
Try as below:
const oFormData = new FormData();
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
return axios.post(postUrl, oFormData);

Image upload with axios react native android

I am trying to upload image to an API the iOS version is working good but there is problem in android, My code is bellow.
const uploadUri =
Platform.OS === 'ios'
? uploadImageFile.replace('file:', '')
: uploadImageFile;
// console.log(uploadUri);
const data = new FormData();
data.append('file', {
uri: uploadUri,
name: 'file',
type: 'image/jpg',
});
Axios.post(`${API.BASE_URL}/user/image`, data, {
headers: {
Authorization: token,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
setActivity(false);
setIsImageEdit(false);
console.log('success');
})
.catch((error) => {
setActivity(false);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
setIsImageEdit(false);
});
The error response I get is
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json, text/plain, */*", "authorization": "7aeb23f62bd748c39c9e8652eb1056e2"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_https://capi-test.beebl.io/user/image", "_requestId": null, "_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "https://capi-test.beebl.io/user/image", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials": true}
"_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg"
I fixed it by adding
android:requestLegacyExternalStorage="true"
in AndroidManifest.xml

How to setup Sanctum in laravel to work with Android apps? Getting 419 error

I have an hybrid vuejs app, that is working correctly on the web version, but that is getting 419 from the Laravel server when calling it from the Android version.
AXIOS CALL
vm.axios.get('/sanctum/csrf-cookie').then(response => {
vm.logging = true;
vm.axios({
method: 'POST',
url: '/api/login/employee',
data:{
email: vm.email,
password: vm.password
},
}).then(function (response) {
console.log(response.data)
if(response.data.success){
vm.axios.defaults.headers.common['Authorization'] = 'Bearer '+response.data.token;
localStorage.setItem('bearer', vm.axios.defaults.headers.common['Authorization']);
vm.$store.commit('updateUserData');
}
}, function (error) {
console.log(error.message)
}).then(function (){
vm.logging = false;
});
});
CORS
'paths' => ['api/*','sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
KERNEL
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];

Does anyone know how to fetch data from json in react native?

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.

how to display data on View after fetching from Json in react native

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.

Categories

Resources