Black Screen after deleting the record - laravel
I am using Laravel as the Backend API and Flutter for the Client. Category Add and Category Update features are working without any issue. However, when i delete a category, the category gets deleted from the database but returns the user to a black page. I am finding difficult to find the error.
lib\screens\categories.dart
import 'package:flutter/material.dart';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/widgets/category_edit.dart';
import 'package:demo_app/providers/category_provider.dart';
import 'package:provider/provider.dart';
// import '../widgets/category_add.dart';
import 'package:demo_app/widgets/category_add.dart';
// import 'package:http/http.dart' as http;
class Categories extends StatefulWidget {
const Categories({super.key});
#override
State<Categories> createState() => _CategoriesState();
}
class _CategoriesState extends State<Categories> {
#override
Widget build(BuildContext context) {
final provider = Provider.of<CategoryProvider>(context);
List<Category> categories = provider.categories;
return Scaffold(
appBar: AppBar(
title: const Text('Categories'),
),
body: ListView.builder(
itemCount: categories.length,
itemBuilder: (context, index) {
Category category = categories[index];
return ListTile(
title: Text(category.name),
trailing:
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) {
return CategoryEdit(category, provider.updateCategory);
});
},
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('confirmation'),
content: const Text('Are you sure you want to delete?'),
actions: [
TextButton(
onPressed: () => deleteCategory(provider.deleteCategory, category),
child: const Text('Confirm')
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel')
),
]
);
}
),
),
],
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext context) {
return CategoryAdd(provider.addCategory);
});
},
child: const Icon(Icons.add)
),
);
}
Future deleteCategory(Function callback, Category category) async{
await callback(category);
if (!mounted) return;
Navigator.pop(context);
}
}
lib\providers\category_provider.dart
import 'package:demo_app/models/category.dart';
import 'package:demo_app/providers/auth_provider.dart';
import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
class CategoryProvider extends ChangeNotifier{
List<Category> categories = [];
late ApiService apiService;
late AuthProvider authProvider;
CategoryProvider(this.authProvider){
apiService = ApiService(authProvider.token);
init();
}
Future init() async{
categories = await apiService.fetchCategories();
notifyListeners();
}
Future<void> addCategory(String name) async{
try{
Category addedCategory = await apiService.addCategory(name);
categories.add(addedCategory);
notifyListeners();
} catch(e){
await authProvider.logOut();
// ignore: avoid_print
// print(e);
}
}
Future<void> updateCategory(Category category) async{
try{
Category updatedCategory = await apiService.updateCategory(category);
int index = categories.indexOf(category);
categories[index] = updatedCategory;
notifyListeners();
} catch(e){
await authProvider.logOut();
}
}
Future<void> deleteCategory(Category category) async{
try{
await apiService.deleteCategory(category.id);
categories.remove(category);
notifyListeners();
} catch(e){
await authProvider.logOut();
}
}
}
lib\services\api.dart
// import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/models/transaction.dart';
// import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ApiService{
late String token;
ApiService(this.token);
final String baseUrl = 'http://flutter-api.test/api/';
Future<List<Category>> fetchCategories() async {
http.Response response =
await http.get(Uri.parse('${baseUrl}categories'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List categories = jsonDecode(response.body);
return categories.map((category) => Category.fromJson(category)).toList();
}
Future <Category> addCategory(String name) async {
String uri = '${baseUrl}categories';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': name}));
if(response.statusCode != 201){
throw Exception('Error happened on create');
}
return Category.fromJson(jsonDecode(response.body));
}
Future <Category> updateCategory(Category category) async {
// String uri = '${baseUrl}categories/$category.id';
String uri = '${baseUrl}categories/${category.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': category.name}));
if(response.statusCode != 200){
throw Exception('Error happened on update');
}
return Category.fromJson(jsonDecode(response.body));
}
Future<void> deleteCategory(id) async {
String uri = '${baseUrl}categories/$id';
http.Response response = await http.delete(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if(response.statusCode != 204){
// // ignore: avoid_print
// ignore: avoid_print
print(response.statusCode);
// ignore: avoid_print
print(response.body.toString());
throw Exception('Error happened on delete');
}
}
Future<List<Transaction>> fetchTransactions() async {
http.Response response = await http.get(
Uri.parse('${baseUrl}transactions'),
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List transactions = jsonDecode(response.body);
return transactions.map((transaction) => Transaction.fromJson(transaction)).toList();
}
Future<Transaction> addTransaction(String amount, String category, String description, String date) async {
String uri = '${baseUrl}transactions';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': amount,
'category_id': category,
'description': description,
'transaction_date': date
}));
if (response.statusCode != 201) {
throw Exception('Error happened on create');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<Transaction> updateTransaction(Transaction transaction) async {
String uri = '${baseUrl}transactions/${transaction.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': transaction.amount,
'category_id': transaction.categoryId,
'description': transaction.description,
'transaction_date': transaction.transactionDate
}));
if (response.statusCode != 200) {
throw Exception('Error happened on update');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<void> deleteTransaction(id) async {
String uri = '${baseUrl}transactions/$id';
http.Response response = await http.delete(
Uri.parse(uri),
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if (response.statusCode != 204) {
throw Exception('Error happened on delete');
}
}
Future<String> register(String name, String email, String password, String passwordConfirm, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/register';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirm,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
Future<String> login(String email, String password, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/login';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'email': email,
'password': password,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
}
lib\providers\auth_provider.dart
import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthProvider extends ChangeNotifier{
bool isAuthenticated = false;
late String token;
late ApiService apiService;
AuthProvider() {
init();
}
Future<void> init() async {
token = await getToken();
if (token.isNotEmpty) {
isAuthenticated = true;
}
apiService = ApiService(token);
notifyListeners();
}
Future<void> register(String name, String email, String password, String passwordConfirm, String deviceName) async{
token = await apiService.register(name, email, password, passwordConfirm, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logIn(String email, String password, String deviceName) async{
token = await apiService.login(email, password, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logOut() async{
token = '';
isAuthenticated = false;
setToken();
notifyListeners();
}
Future<void> setToken() async{
final pref = await SharedPreferences.getInstance();
pref.setString('token', token);
}
Future<String> getToken() async {
final pref = await SharedPreferences.getInstance();
final token = pref.getString("token") ?? "";
return token;
}
}
lib\main.dart
import 'package:demo_app/providers/auth_provider.dart';
import 'package:demo_app/providers/transaction_provider.dart';
import 'package:demo_app/screens/home.dart';
import 'package:demo_app/screens/login.dart';
import 'package:demo_app/screens/register.dart';
import 'package:demo_app/screens/categories.dart';
// import 'package:demo_app/screens/transactions.dart';
import 'package:flutter/material.dart';
import 'package:demo_app/providers/category_provider.dart';
import 'package:provider/provider.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget{
const MyApp({super.key});
#override
Widget build(BuildContext context){
return ChangeNotifierProvider(
create: (context) => AuthProvider(),
child: Consumer<AuthProvider>(builder: (context, authProvider, child){
return MultiProvider(
providers: [
ChangeNotifierProvider<CategoryProvider>(
create: (context) => CategoryProvider(authProvider)),
ChangeNotifierProvider<TransactionProvider>(
create: (context) => TransactionProvider(authProvider)),
],
child: MaterialApp(
title:'Welcome to Flutter',
routes: {
'/': (context) {
final authProvider = Provider.of<AuthProvider>(context);
if(authProvider.isAuthenticated){
return const Home();
}else{
return const Login();
}
},
'/login': (context) => const Login(),
'/register': (context) => const Register(),
'/categories': (context) => const Categories(),
}));
}
)
);
}
}
lib\screens\categories.dart
Future deleteCategory(Function callback, Category category, BuildContext context) async{
await callback(category);
if (!mounted) return;
Navigator.pop(context);
}
Solved the issue
I changed the headers in the lib\services\api.dart too
lib\services\api.dart
looks like this
// import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/models/transaction.dart';
// import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ApiService{
late String token;
ApiService(this.token);
final String baseUrl = 'http://flutter-api.test/api/';
Future<List<Category>> fetchCategories() async {
http.Response response =
await http.get(Uri.parse('${baseUrl}categories'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List categories = jsonDecode(response.body);
return categories.map((category) => Category.fromJson(category)).toList();
}
Future <Category> addCategory(String name) async {
String uri = '${baseUrl}categories';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': name}));
if(response.statusCode != 201){
throw Exception('Error happened on create');
}
return Category.fromJson(jsonDecode(response.body));
}
Future <Category> updateCategory(Category category) async {
String uri = '${baseUrl}categories/${category.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': category.name}));
if(response.statusCode != 200){
throw Exception('Error happened on update');
}
return Category.fromJson(jsonDecode(response.body));
}
Future<void> deleteCategory(id) async {
String uri = '${baseUrl}categories/$id';
http.Response response = await http.delete(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if(response.statusCode != 204){
// // ignore: avoid_print
// ignore: avoid_print
print(response.statusCode);
// ignore: avoid_print
print(response.body.toString());
throw Exception('Error happened on delete');
}
}
Future<List<Transaction>> fetchTransactions() async {
http.Response response = await http.get(
Uri.parse('${baseUrl}transactions'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List transactions = jsonDecode(response.body);
return transactions.map((transaction) => Transaction.fromJson(transaction)).toList();
}
Future<Transaction> addTransaction(String amount, String category, String description, String date) async {
String uri = '${baseUrl}transactions';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': amount,
'category_id': category,
'description': description,
'transaction_date': date
}));
if (response.statusCode != 201) {
throw Exception('Error happened on create');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<Transaction> updateTransaction(Transaction transaction) async {
String uri = '${baseUrl}transactions/${transaction.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': transaction.amount,
'category_id': transaction.categoryId,
'description': transaction.description,
'transaction_date': transaction.transactionDate
}));
if (response.statusCode != 200) {
throw Exception('Error happened on update');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<void> deleteTransaction(id) async {
String uri = '${baseUrl}transactions/$id';
http.Response response = await http.delete(
Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if (response.statusCode != 204) {
throw Exception('Error happened on delete');
}
}
Future<String> register(String name, String email, String password, String passwordConfirm, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/register';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirm,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
Future<String> login(String email, String password, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/login';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'email': email,
'password': password,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
}
Related
Why does flutter app always crash after debugging
this is the main.dart file if there is anyone can help me. after crashing it stuck on this message : Launching lib\\main.dart on sdk gphone x86 arm in debug mode... lib\\main.dart:1 √ Built build\\app\\outputs\\flutter-apk\\app-debug.apk. like this import 'package:dio/dio.dart'; class BaseUrl { static String url = 'https://awad.mohatim.tech/public/api'; static String real = 'https://awad.mohatim.tech/api/'; static String local = 'http://127.0.0.1:8000/api/'; } Map<String, String> headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', }; class DioHelper { static final BaseOptions _options = BaseOptions( baseUrl: BaseUrl.real, headers: headers, validateStatus: (status) { return status! < 500; }, ); static final Dio _dio = Dio(_options); // get login # data = email and password static Future getLogin({required Map<String, dynamic> data}) async { try { Response response = await _dio.post('login', data: data); return response; } on DioError catch (e) { print(e.message); } } // data = name email phone paswword static Future register({required Map<String, dynamic> data}) async { try { Response response = await _dio.post('register', data: data); return response; } on DioError catch (e) { print(e.message); } } // public request static Future post({required String endpoint, required dynamic data}) async { Map<String, String> headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', }; try { Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers)); return response; } on DioError catch (e) { print(e.message); } } // public request static Future get({required String endpoint}) async { try { Response response = await _dio.get(endpoint); return response; } on DioError catch (e) { print(e.message); } } static Future getWithToken({required String endpoint, required String token}) async { Map<String, String> headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', }; try { Response response = await _dio.get(endpoint, options: Options(headers: headers)); return response; } on DioError catch (e) { print(e.message); } } static Future postWithToken({required String endpoint, required dynamic data, required String token}) async { Map<String, String> headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', }; try { Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers)); return response; } on DioError catch (e) { print(e.message); } } static Future postImage({required String endpoint, required FormData data, required String token}) async { Map<String, String> headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', }; try { Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers)); return response; } on DioError catch (e) { print(e.message); } } } I'm trying to connect the app with Laravel admin panel throw API
Flutter app gave an error after performing the necessary integration with laravel api, it returned null
I have a signup page having done all the necessary integration my flutter app still not posting Here I have my signup method _signup() async { var data = { 'first': firstNameController.text, 'last': lastNameController.text, 'email': emailController.text, 'phone': phoneController.text, 'age': ageController.dropDownValue!.name, 'gender': genderController.dropDownValue!.name, 'password': passwordController.text, 'confirm': confirmPasswordController.text }; print(data); var res = await CallApi().postData(data, 'register'); print(res); var body = json.decode(res.body); print(body); } Why I have the api authentication here which is well configured import 'package:http/http.dart' as http; class CallApi { final String baseURL = 'https://beereapp.edusmart.ng/api/auth/'; postData(data, apiUrl) async { var fullUrl = baseURL + apiUrl; return await http.post( Uri.parse(fullUrl), body: jsonEncode(data), headers: _setHeaders()); } getData(apiUrl) async { var fullUrl = Uri.parse(baseURL + apiUrl); return await http.get(fullUrl, headers: _setHeaders()); } _setHeaders() => { 'Content-type': 'application/json', 'Accept': 'application/json', }; } As you can see my terminal below I printed my data out which is showing but next is error. Help please! [![My terminal][1]][1] [1]: https://i.stack.imgur.com/10uMa.jpg
React custom hook for different API task with unique state and handling management in each?
I had already written custom API fetch hooks before, but now I have complex API call functions with different features and couldn't wrap my head around how to create a single custom hook and use all of them. Each of them got different states, methods, wrappers etc some with a single promise some with promise.all() 1st call: const handleGetReportsList = async () => { setIsLoading(true); try { const response = await axios(reportURL, { method: "GET", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token } }); setReportsList(response.data); } catch (err) { if (axios.isAxiosError(err)) { console.log(err.response); notify( { width: "auto", message: `Rapor verileri listelenemiyor. ${err.response?.data.message} Hata kodu: ${err.response?.status}`, position: {} }, "error", 6000 ); console.error( (err instanceof Error && err.message) || "Something's Wrong" ); } else { notify("Hata! Çıkış yapıp tekrar deneyin", "error", 6000); } } setIsLoading(false); }; 2nd call: const handleGetReportData = async (e: ClickEvent) => { const validationResult = e.validationGroup.validate(); if (validationResult.isValid) { setIsLoading(true); setIsDataGridVisible(false); try { const response = await axios(reportURL, { method: "POST", data: JSON.stringify(reportParams), headers: { "Content-Type": "application/json", Authorization: "Bearer " + token } }); setReportData(response.data); setIsDataGridVisible(true); } catch (err) { setIsLoading(false); if (axios.isAxiosError(err)) { notify( { width: "auto", message: `Rapor verileri listelenemiyor. Lütfen tekrar deneyin. Hata kodu: ${err.response?.status}` }, "error", 6000 ); console.error( (err instanceof Error && err.message) || "Something's Wrong" ); } else { notify("Hata! Çıkış yapıp tekrar deneyin", "error", 6000); } } } }; 3rd call: const handleGetFilterData = async () => { setIsLoading(true); setIsFilterButtonVisible(false); try { const response = await axios(filterURL, { method: "GET", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token } }); // eslint-disable-next-line #typescript-eslint/no-explicit-any dispatchFilterData(response.data); setIsFilterButtonVisible(true); } catch (err) { if (axios.isAxiosError(err)) { notify( { width: "auto", message: `Rapor verileri listelenemiyor. Lütfen tekrar deneyin. Hata kodu: ${err.response?.data.message}` }, "error", 6000 ); console.error( (err instanceof Error && err.message) || "Something's Wrong" ); } else { notify("Hata! Çıkış yapıp tekrar deneyin", "error", 6000); } } setIsLoading(false); }; 4th call: const getDashboardData = async () => { const apiSettings: AxiosRequestConfig<IApiSettings> = { method: "GET", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token } }; setIsLoading(true); try { const response = await Promise.all([ axios(`${dashboardURL}TOPLAM/${period}/`, apiSettings), axios(`${dashboardURL}ADET/${period}/`, apiSettings) ]); const responseData = response.map(item => { return item.data; }); setDashboardData(responseData); } catch (err) { if (axios.isAxiosError(err)) { console.log(err.response); notify( { width: "auto", message: `Özet verileri listelenemiyor. ${err.response?.data.message} Hata kodu: ${err.response?.status}`, position: { offset: "0 -100" } }, "error", 6000 ); console.error( (err instanceof Error && err.message) || "Something's Wrong" ); } else { notify("Hata! Çıkış yapıp tekrar deneyin", "error", 6000); } } setIsLoading(false); }; As the calls are pretty similar I want to create and use hooks. Cheers
authClient is not called with the AUTH_ERROR
I'm trying to implement custom rest client build on top of simple fetch. If 401-403 response received, it must "redirect" app to login page. According documentation, if 401-403 error received, it will magically calls authClient with the AUTH_ERROR, but it doesn't. Can someone explain, how to connect it? I'm trying to call rest client from component: It's simple reimplementation of 'simpleRestClient' componentDidMount() { restClient(CREATE, 'api/method', { CurrentTime: new Date() }) .then(o => { this.setState({ Msg: Object.values(o.data.ServerTime) }); }); } restclient implementation: export const fetchJson = (url, options = {}) => { const requestHeaders = options.headers || new Headers({ Accept: 'application/json', }); if ( !requestHeaders.has('Content-Type') && !(options && options.body && options.body instanceof FormData) ) { requestHeaders.set('Content-Type', 'application/json'); } if (options.user && options.user.authenticated && options.user.token) { requestHeaders.set('Authorization', options.user.token); } return fetch(url, { ...options, headers: requestHeaders }) .then(response => response.text().then(text => ({ status: response.status, statusText: response.statusText, headers: response.headers, body: text, })) ) .then(({ status, statusText, headers, body }) => { if (status < 200 || status >= 300) { return Promise.reject( new HttpError( (json && json.message) || statusText, status, json ) ); } let json; try { json = JSON.parse(body); } catch (e) { // not json, no big deal } return { status, headers, body, json }; }); }; const httpClient = (url, options = {}) => { if (!options.headers) { options.headers = new Headers({ Accept: 'application/json' }); } return fetchJson(url, options); }
Have you tried rejecting the promise with an Error rather than an HttpError?
How call WebAPi in phonegap?
I am calling Web API by using Datajs and it is working in each browser but when i am calling this by Phonegap then i am getting error Http Request failed. function DefaultHandler() { var oldDefaultHandler = OData.defaultHandler; OData.defaultHandler = { accept: oldDefaultHandler.accept, read: function (response, context) { var contentType = response.headers["Content-Type"]; if (contentType && contentType.indexOf("text/html") === 0) { response.data = response.body; } else { oldDefaultHandler.read(response, context); } }, write: function (request, context) { oldDefaultHandler.write(request, context); } }; } function GetContact() { $('#products').html(''); OData.defaultHttpClient.enableJsonpCallback = true; DefaultHandler(); OData.read( { requestUri: "http://192.168.11.46/odata/Contact", enableJsonpCallback: false, datatype: "json", headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Content-Type': 'application/json', 'Accept': 'text/html', "Authorization-Token": "94,214,182,1,98,51,181,18,190,167,152,19,225,97,211,221,145,78,188,26,247,172,226,13,90,113,105,2,226,15,137,12,190,22,95,226,215,9,111,95,162,33,36,220,238,197,99,169,158,140,170,61,3,186,190,97,244,173,125,212,3,135,172,111,235,229,133,101,234,188,104,188,127,10,188,221,72,120,48,25,184,56,215,80,87,83,117,30,57,241,133,80,137,220,185,220,230,0,20,122,181,0,106,69,234,27,106,212,187,77,77,27,39,159,31,253,140,105,43,167,210,238,35,71,44,251,180,199" }, method: "GET" }, success, error ); } success = function (data) { alert('success Odata'); }; error = function (err) { alert('error Odata'); }; Is there any setting that i need to set in Eclipse or in emulator.