why is my flutter app sending unlimited request - android

while trying to get the list of countries from my api, my code is sendig unlimited request to the server when i call the function one time. here is the flutter code
Future<dynamic> listePays() async{
http.Response response = await http.get(apiUrl+"api_pays", headers: {"Accept": "application/json"});
var resp = json.decode(response.body);
return resp;
}
i want to send just one request and work with the answers. ihave tried removing Future but i get the same issue
i call the function like this:
getPays() async {
Functions().listePays().then((data) async {
pays = data;
setState(() {});
});
}

Related

Fetch DELETE method on Android (React Native)

I make several requests from a React Native app to an API. Every request works fine both on iOS and Android except the DELETE method that does not work on Android. The call is correctly made, it goes through the API and the objects are deleted. But instead of getting the response, the call falls under the catch statement with [TypeError: Network request failed]. This does not happen in iOS.
Some people with the same problem were missing 'Content-Type': 'application/json' on the request headers which is not my case.
This is happening both locally, in testing and production stages (using an ip instead of localhost will do nothing).
The request is also successfully performed in Postman.
What can it be?
React Native 0.63.5
export const deleteApi = async (api: string, body?: any) => {
const userResponse = await getUserCredentials();
const authState = await getAuthState();
let response = await fetch(api, {
method: 'DELETE',
headers: await getHeaders(userResponse, authState),
body: JSON.stringify(body)
});
if (response.status === UNAUTHENTICATED_CODE)
response = await interceptor(response, userResponse, {
api: api,
method: 'DELETE',
body: body
});
return response;
};
leaveClass = async (
uuid: string,
onSuccess: () => void,
onFailure: (error: string) => void,
) => {
this.setLoading(true);
try {
const api = LEAVE_CLASS_API_PREFIX + uuid + LEAVE_CLASS_API_SUFFIX;
const response = await deleteApi(api);
if (response.status === SUCCESS_STATUS_CODE) {
onSuccess();
}
else {
const jsonResponse = await response.json();
if (jsonResponse.detail) onFailure(jsonResponse.detail);
else onFailure(translations.SOMETHING_WENT_WRONG);
}
} catch (error) {
console.log('leaveClass error: ', error);
}
this.setLoading(false);
};
You can use a network plugin for Flipper (https://fbflipper.com/docs/setup/plugins/network/), copy your request from it as a curl, and try to perform it from your terminal or postman. If it has the same error, the problem is not in React Native.

Flutter while refreshToken getting old refresh token

I making refresh token with dio interceptors. Its working well but while i have multiple request in same time its trying using old refresh token. What can i do for fix it ? I tried use QueuedInterceptorsWrapper too but it has same result. Let me show you my codes first :
My Interceptor on constructor.
_dio.interceptors.add(
InterceptorsWrapper(onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) {
return handler.next(response);
}, onError: (DioError error, ErrorInterceptorHandler handler) async {
if (error.response?.statusCode == 401) {
var options = error.response!.requestOptions;
if ("Bearer $accessToken" != options.headers[HttpHeaders.authorizationHeader]) {
options.headers[HttpHeaders.authorizationHeader] = "Bearer $accessToken";
_dio.fetch(options).then((value) => handler.resolve(value), onError: (err) {
log("error on fetchiN!!!!");
});
// log("$accessToken ////// ${_dio.options.headers["Authorization"]}");
}
final refToken = await UserSecureStorage.getField("refreshToken");
if (refToken != null) {
log("hata alındı ${error.requestOptions.path}");
await refreshToken(refToken);
return handler.resolve(await _retry(error.requestOptions));
}
}
return handler.next(error);
}, onRequest: (RequestOptions options, RequestInterceptorHandler handler) async {
log("request atıldı ${options.path} ---Ref token => ${await UserSecureStorage.getField("refreshToken")}");
if (accessToken == null) {
accessToken = await UserSecureStorage.getField("token");
}
options.headers["Authorization"] = "Bearer $accessToken";
return handler.next(options);
}),
);
Refresh token function
Future<void> refreshToken(String? refreshToken) async {
final refToken = await UserSecureStorage.getField("refreshToken");
//In first request its changing and its working fine. But while it have multiple request in same time while in second request its trying use old refreshtoken
//token dio is another instance of dio so it hasnt any interceptor.Its only has baseurl.
final response = await tokenDio.get("/Auth/RefreshTokenLogin?
refreshToken=${Uri.encodeQueryComponent(refToken!)}");
if (response.statusCode == 200) {
final RefreshTokenResponseModel? model =
RefreshTokenResponseModel.fromJson(response.data);
accessToken = model!.data!.token;
log("refreshlendi! Yenisi => ${model.data!.refreshToken}");
await UserSecureStorage.setField("token", model.data!.token);
await UserSecureStorage.setField("refreshToken", model.data!.refreshToken);
_dio.options.headers[HttpHeaders.authorizationHeader] = "Bearer ${model.data!.token}";
}
}
Some screenshoots for make it clear.
Request sent to notification.
Request sent to therapist
Get error on notification
Request sent to PurchasedPackages
Get error on PurchasedPackages
Token refreshed. New token +pVX....
Error on another instance of dio for refresh token without any interceptor.
Refreshtoken instance tried refresh it with old refresh token.Ke.... So its gaving DioError on refreshtoken instance.
What can i do for fix it ? Thanks for response!

Can't get Future Value from DIO Flutter

I'm really new in Flutter programming. I've problem while try to get value from Future. After I get it, I want to deserialize it for further processing.
The return value from the Future is on JSON Array.
What should I do to solve this situation?
class _MyAppState extends State<BodyWidget>
{
bool loading = true;
List<Widget> listArray = [];
Dio dio = new Dio();
dynamic isicontent = null;
Future<dynamic> getOrderHistory() async {
final String pathUrl = "http://p.q.r.s/mobile/QIXGetShipmentHistory/" + await FlutterSession().get("MobileUsername");
var responseDio = await dio.get(pathUrl, options: Options( headers: {'Content-Type': 'application/json; charset=UTF-8' } ) );
print(responseDio.data); // It's works fine here...
return responseDio.data;
}
void renderIconShipmentOrderHistory()
{
var resultRespon = getOrderHistory();
print(resultRespon); //the problem is here...
}
}
The return statement needs to return a Future; something alike:
return dio.get(
pathUrl,
options: Options(
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
)
)
The async keyword from the signature likely can be removed, as there is no more await.
Obviously, not returning a Future but awaiting the result may be the other option.

Flutter http.response doesn't get any response

i'm trying to get a simple response from http.Response. My code was working a few days ago and the only change from then to now was my location.
[...]
http.Response resp = await http.get(
Uri.encodeFull('$apiUrl/tblColMain'),
headers: {
"Accept": "application/json"
}
);
print(resp);
var data = json.decode(resp.body);
print(data);
This code doesn't print anything and shows no errors, I don't know what I'm doing wrong.
Thanks for any help!

Firebase Performance Monitoring React Native integration

I have install Firebase Performance monitoring on my React Native app
and integrate it successfully. After i want to track my network requests performance and go through as documentation.
const trackRequest = async (url,method) => {
// Define the network metric
const metric = await perf().newHttpMetric(url, method);
// Define meta details
metric.putAttribute('testAttr', 'testValue');
// Perform a HTTP request and provide response information
const response = await fetch(url);
metric.setHttpResponseCode(response.status);
metric.setResponseContentType(response.headers.get('Content-Type'));
metric.setResponsePayloadSize(response.headers.get('Content-Length'));
// Stop the trace
await metric.stop();
return response.json();
};
I use this function from documentation and call it every network requests time
fetch("www.example.com")
trackRequest("www.example.com","GET")
Can anyone explain me what i were doing wrong ?
It looks like you're not using the API correctly. There appears to be a good example in the documentation. You need to call start() on the metric before calling stop(). Also, the example shows that you should use await on each method call, but I don't really know if that's necessary.
const trackRequest = async (url,method) => {
const metric = await perf().newHttpMetric(url, method);
// !!! Don't forget to call start()
await metric.start();
await metric.putAttribute('testAttr', 'testValue');
const response = await fetch(url);
await metric.setHttpResponseCode(response.status);
await metric.setResponseContentType(response.headers.get('Content-Type'));
await metric.setResponsePayloadSize(response.headers.get('Content-Length'));
// Stop the trace only after you started it
await metric.stop();
return response.json();
};

Categories

Resources