Expo FCM push notification sound not working - android

I have tried this code:
const sendPushNotification = async (vendor_token, user_message) => {
const message = {
to: vendor_token,
priority: Platform.OS === 'android' ? "normal" : "high",
sound: "default",
title: 'Order Detail',
body: user_message,
data: { data: 'goes here' },
_displayInForeground: true,
};
const response = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
const data = response._bodyInit;
console.log(`Status & Response ID-> ${JSON.stringify(data)}`);
};
But if add sound: true for Android notification not working.

const sendPushNotification = async (vendor_token, user_message) => {
const message = {
to: vendor_token,
priority: Platform.OS === 'android' ? "normal" : "high",
sound: "default",
title: 'Order Detail',
body: user_message,
data: { data: 'goes here' },
_displayInForeground: true,
channelId: "chat-messages",`enter code here`
};
const response = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
const data = response._bodyInit;
console.log(`Status & Response ID-> ${JSON.stringify(data)}`);
};
Just add "channelId: "chat-messages" in the code and android notification sound is working perfectly

Related

Firebase Messaging - how to prevent the SDK generated notification from appearing?

I am building a Flutter app with Firebase Messaging. I am using AwesomeNotifications plugin to display the notifications.
My notifications contain the notification property, because sending data only message does not trigger the iOS if the device is rebooted.
The issue with the notification property is that it triggers flutter SDK and auto display the default notification alone with the custom notification I configured with AwesomeNotifications .
Below is my JSON code.
"message": {
"notification": {
"title": senderName,
"body": "Image Sent"
},
"token": recieverFcm,
"data": {
"name": senderName,
"body": "Image Sent",
"chatRoomId": chatRoomId,
"sender_profile_pic": senderProfilePic,
"senderUid": senderUid,
"data_type": messageType,
"image_link": message,
"click_action": "OPEN_CHAT_ROOM"
},
"android": {
"priority": "high"
},
"apns": {
"payload": {
"aps": {
"category": "OPEN_CHAT_ROOM",
"sound": "enable",
"content-available": 1,
}
}
}
}
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
NotificationController _notificationController = NotificationController();
//Initialize firebase
await Firebase.initializeApp();
await _notificationController.startNotificationService();
//Listen for the Token change
FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
print("New token: $token");
});
//Apply MultiProvider
runApp(MultiProvider(
providers: [
//provider lists
],
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
NotificationController _notificationController = NotificationController();
_notificationController.startAwesomeNotificationlistener();
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
textTheme: GoogleFonts.poppinsTextTheme(),
primaryColor: primaryColor,
backgroundColor: Colors.white,
scaffoldBackgroundColor: Colors.white,
accentColor: darkColor,
appBarTheme: AppBarTheme(
backgroundColor: Colors.white,
elevation: 0,
iconTheme: IconThemeData(color: Colors.black),
titleTextStyle: GoogleFonts.poppins(
fontSize: 16, color: darkColor, fontWeight: FontWeight.w500)),
textSelectionTheme: TextSelectionThemeData(cursorColor: darkColor),
outlinedButtonTheme: OutlinedButtonThemeData(style: outlineButtonStyle),
elevatedButtonTheme:
ElevatedButtonThemeData(style: elevatedButtonStyle),
),
routes: {
//Routes go here
},
home: LoadingScreen3(),
);
}
}
notification_controller.dart
class NotificationController {
///Start notification service
Future<void> startNotificationService() async {
NotificationService _notificationService = NotificationService();
await _notificationService.initializFirebaseeNotifications();
}
///Display a new notification in foreground
Future<void> displayNotification({
required String groupKey,
required String channelKey,
required String title,
required String body,
required String summary,
required NotificationLayout layout,
required bool displayOnBackground,
required bool displayOnForeground,
required String messageType,
String? clickAction,
String? chatRoomId,
String? chatMessageFrom,
}) async {
NotificationService _notificationService = NotificationService();
await _notificationService.createAwesomeNotification(
groupKey: groupKey,
channelKey: channelKey,
title: title,
body: body,
summary: summary,
layout: layout,
displayOnBackground: displayOnBackground,
displayOnForeground: displayOnForeground,
messageType: messageType,
clickAction: clickAction,
chatRoomId: chatRoomId,
chatMessageFrom: chatMessageFrom);
}
//Start awesome notification listener
void startAwesomeNotificationlistener() {
NotificationService _notificationService = NotificationService();
_notificationService.startAwesomeNotificationListener();
}
}
notification_service.dart
class NotificationService with ChangeNotifier {
FirebaseMessaging _messaging = FirebaseMessaging.instance;
///Start initializing the notification service
Future<void> initializFirebaseeNotifications() async {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
//Request permission for firebase messaging
NotificationSettings settings = await _messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
developer.log("REMOTE MESSAGE LISTENER");
print("REMOTE MESSAGE LISTENER");
if (message.data["data_type"] == "TEXT") {
await createAwesomeNotification(
groupKey: message.data["senderUid"],
channelKey: 'basic_channel',
title: message.data["name"],
body: message.data["body"],
summary: message.data["body"],
layout: NotificationLayout.Messaging,
displayOnBackground: true,
displayOnForeground: true,
messageType: message.data["data_type"],
clickAction: message.data["click_action"],
chatRoomId: message.data["chatRoomId"],
chatMessageFrom: message.data["senderUid"]);
} else if (message.data["data_type"] == "IMAGE") {
await createAwesomeNotification(
groupKey: message.data["senderUid"],
channelKey: 'basic_channel',
title: message.data["name"],
body: Emojis.art_framed_picture + " " + message.data["body"],
summary: message.data["body"],
layout: NotificationLayout.Messaging,
displayOnBackground: true,
displayOnForeground: true,
messageType: message.data["data_type"],
clickAction: message.data["click_action"],
chatRoomId: message.data["chatRoomId"],
chatMessageFrom: message.data["senderUid"],
);
}
});
} else {
print('User declined or has not accepted permission');
}
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage? message) {
developer.log("REMOTE MESSAGE");
if (message != null) {
developer.log(message.data.toString());
}
});
// For handling notification when the app is in background
// but not terminated
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("onMessageOpenedApp executed");
});
await initializeAwesomeNotifications();
}
//Initialize the notification display plugin
Future<void> initializeAwesomeNotifications() async {
AwesomeNotifications().initialize('resource://drawable/logo', [
NotificationChannel(
channelGroupKey: 'basic_tests',
channelKey: 'basic_channel',
channelName: 'Basic notifications',
channelDescription: 'Notification channel for basic tests',
defaultColor: Color(0xFF9D50DD),
ledColor: Colors.white,
importance: NotificationImportance.High),
]);
}
//Create and display notification
Future createAwesomeNotification({
required String groupKey,
required String channelKey,
required String title,
required String body,
required String summary,
required NotificationLayout layout,
required bool displayOnBackground,
required bool displayOnForeground,
required String messageType,
String? clickAction,
String? chatRoomId,
String? chatMessageFrom,
}) async {
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: UniqueKey().hashCode,
groupKey: groupKey,
channelKey: channelKey,
title: title,
body: body,
summary: summary,
notificationLayout: layout,
displayOnBackground: displayOnBackground,
displayOnForeground: displayOnForeground,
payload: {
"messageType": messageType,
"clickAction": clickAction ?? "",
"chatRoomId": chatRoomId ?? "",
"chatMessageFrom": chatMessageFrom ?? ""
}),
);
}
//Start Awesome notification listener
void startAwesomeNotificationListener() {
AwesomeNotifications()
.actionStream
.listen((ReceivedNotification receivedNotification) {
developer.log("Notification clicked");
developer.log(receivedNotification.body ?? "no data");
});
}
}
// Declared as global, outside of any class
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
NotificationController _notificationController = NotificationController();
developer.log("background listener called");
print("Handling a background message: ${message.data}");
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
// Use this method to automatically convert the push data, in case you gonna use our data standard
//AwesomeNotifications().createNotificationFromJsonData(message.data);
if (message.data['data_type'].toString().toUpperCase() == "TEXT") {
print("Handling a background message: ${message.data['data_type']}");
await _notificationController.displayNotification(
groupKey: message.data["senderUid"],
channelKey: 'basic_channel',
title: message.data["name"],
body: message.data["body"],
summary: message.data["body"], // Anything you want here
layout: NotificationLayout.Messaging,
displayOnForeground: true,
displayOnBackground: true,
messageType: message.data["data_type"],
clickAction: message.data["click_action"],
chatRoomId: message.data["chatRoomId"],
chatMessageFrom: message.data["senderUid"]);
} else if (message.data['data_type'].toString().toUpperCase() == "IMAGE") {
Future.delayed(Duration(seconds: 2));
await _notificationController.displayNotification(
groupKey: message.data["senderUid"],
channelKey: 'basic_channel',
title: message.data["name"],
body: Emojis.art_framed_picture + " " + message.data["body"],
summary: message.data["body"], // Anything you want here
layout: NotificationLayout.Messaging,
displayOnBackground: true,
displayOnForeground: true,
messageType: message.data["data_type"],
clickAction: message.data["click_action"],
chatRoomId: message.data["chatRoomId"],
chatMessageFrom: message.data["senderUid"]);
}
}
How can I fix this issue and stop showing the custom created AwesomeNotifications only?

Notification show twice on flutter

I'm stuck. My notification in the background show twice. But in the foreground only one notification. This is my code
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
if(
!AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
!AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)
){
// print('message also contained a notification: ${message.notification.body}');
String imageUrl;
imageUrl ??= message.notification.android?.imageUrl;
imageUrl ??= message.notification.apple?.imageUrl;
print(imageUrl);
if(imageUrl == null){
var id = Random().nextInt(2147483647);
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: id,
title: message.notification.title,
body: message.notification.body,
color: Colors.orange,
customSound: 'resource://raw/alert',
notificationLayout: NotificationLayout.BigText,
channelKey: 'basic_channel_background',
payload: {'data':message.data['payload']}
),
actionButtons: [
NotificationActionButton(
label: 'Lihat Selengkapnya',
enabled: true,
buttonType: ActionButtonType.Default,
key: 'background',
)
]
);
}else{
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: Random().nextInt(2147483647),
title: message.notification.title,
body: message.notification.body,
bigPicture: imageUrl,
color: Colors.orange,
customSound: 'resource://raw/alert',
notificationLayout: NotificationLayout.BigPicture,
channelKey: 'basic_channel_background',
payload: {'data':message.data['payload']}
),
actionButtons: [
NotificationActionButton(
label: 'Lihat Selengkapnya',
enabled: true,
buttonType: ActionButtonType.Default,
key: 'background',
)
]
);
}
}
}
// End Background Message
and this is my foreground code
// Foreground Apps
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
await AwesomeNotifications().initialize(
'resource://mipmap/launcher_icon',
[
NotificationChannel(
channelGroupKey: 'basic_tests',
channelKey: 'basic_channel',
channelName: 'My Cahaya Notification',
channelDescription: 'Notification channel for basic tests',
icon: 'resource://mipmap/launcher_icon',
importance: NotificationImportance.High,
playSound: true,
soundSource: 'resource://raw/alert'
),
NotificationChannel(
channelGroupKey: 'basic_background',
channelKey: 'basic_channel_background',
channelName: 'My Cahaya Notification Background',
channelDescription: 'Notification channel for basic tests',
icon: 'resource://mipmap/launcher_icon',
importance: NotificationImportance.High,
playSound: true,
soundSource: 'resource://raw/alert'
),
], debug: true);
AwesomeNotifications().actionStream.listen((event) async{
print('event received!');
var data = event.toMap();
if(data['buttonKeyPressed'] == "background"){
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("Navigate", data['payload']['data']);
}else{
_navigateToItemForeground(data['payload']['data']);
}
// do something based on event...
// AwesomeNotifications().actionSink.close();
});
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) async{
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
if(!AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
!AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)){
print("something");
String imageUrl;
imageUrl ??= notification.android?.imageUrl;
imageUrl ??= notification.apple?.imageUrl;
if(imageUrl == null){
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: Random().nextInt(2147483647),
title: notification.title,
body: notification.body,
color: Colors.orange,
customSound: 'resource://raw/alert',
notificationLayout: NotificationLayout.BigText,
channelKey: 'basic_channel',
payload: {'data':message.data['payload']}
),
actionButtons: [
NotificationActionButton(
label: 'Lihat Selengkapnya',
enabled: true,
buttonType: ActionButtonType.Default,
key: 'test',
)
]
);
}else{
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: Random().nextInt(2147483647),
title: notification.title,
body: notification.body,
bigPicture: imageUrl,
color: Colors.orange,
customSound: 'resource://raw/alert',
notificationLayout: NotificationLayout.BigPicture,
channelKey: 'basic_channel',
payload: {'data':message.data['payload']}
),
actionButtons: [
NotificationActionButton(
label: 'Lihat Selengkapnya',
enabled: true,
buttonType: ActionButtonType.Default,
key: 'test',
)
]
);
}
}
}
});
runApp(MyApp());
}
// End Foreground Apps
and this is my screenshot
screenshot
I've tried changing the awesome notification but the result is the same. Could you help me to solve that? I hope you can help me. Thank you very much
FCM payload
{
"to":"_some_fcm_token_",
//remove this
"notification": {
"title": "this is title",
"body": "this is subtitle"
},
"type": "post_like",
"data": {
"model":{"id":"dsaflkdskfklgdkgjdksakdk"},
"body": "this is subtitle",
"title": "this is title",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"priority": "normal"
}
The first one is manually created (locally), and the other one is automatic by Firebase.
When sending a message to your device, make sure it is a notification rather than data. The documentation mentions that if you send data it will likely be ignored as a push notification. Only use it to send packets of data to the app instead.
If your Notification is sent while the App is in background, Firebase
automatically sends a Push-Notification, so you don't need to call the show Notification manually in the App.
I solved the problem like this:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (message.notification != null) {
//No need for showing Notification manually.
//For BackgroundMessages: Firebase automatically sends a Notification.
//If you call the flutterLocalNotificationsPlugin.show()-Methode for
//example the Notification will be displayed twice.
}
return;
}
Solved)
**{
"to":"_some_fcm_token_",
//remove this
//"notification": {
// "title": "this is title",
// "body": "this is subtitle"
},
"type": "post_like",
"data": {
"model":{"id":"dsaflkdskfklgdkgjdksakdk"},
"body": "this is subtitle",
"title": "this is title",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"priority": "normal"
}**
payload: Platform.isAndroid?
json.encode(message.data):json.encode(message.notification)
set payload data like this

Capacitor Push Notification not working in Android

I have set up the Ionic/Capacitor app to receive push notifications following the capacitor tutorial,
I went through all the tutorial successfully and I receive test notifications sent from FCM both in foreground and background
I can successfully register to a topic
I can receive notifications sent to the topic
I can receive notifications sent to the token (test mode)
Now I'm trying to send notifications from a different device,
I just created a two test button to send notification in multicast to an array of tokens and another button to send notification to a given topic
In both cases from my device I receive the notifications in foreground, but not in background
I believe is something wrong with the format I'm using to send the notifications that is not correct in case of background (I can receive those from the FCM test tool)
Client
const send = functions.httpsCallable('sendPushNotificationToUsers');
const sendToTopic = functions.httpsCallable('sendPushNotificationToTopic');
const sendNotification = useCallback(
({
to,
title,
body,
onClick
}) => {
setLoading(true);
send({
to,
title,
body,
onClick
})
.then(() => setSuccess(true))
.catch(() => setError(true))
.finally(() => setLoading(false));
}, [send],
);
const sendNotificationToTopic = useCallback(
({
topic,
title,
body,
onClick
}) => {
setLoading(true);
sendToTopic({
topic,
title,
body,
onClick
})
.then(() => setSuccess(true))
.catch(() => setError(true))
.finally(() => setLoading(false));
}, [sendToTopic],
);
Server / Functions
exports.sendPushNotificationToUsers = functions.https.onCall(
(data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called ' + 'while authenticated.',
);
}
db.collection('users_meta')
.doc(data.to)
.collection('messagingTokens')
.get()
.then(messagingTokens => {
if (messagingTokens && messagingTokens.size) {
const to = messagingTokens.docs.map(i => i.data().token);
console.log(to); // I get to this console log and the tokens are printed correctly in an array
admin.messaging().sendMulticast({
title: data.title,
body: data.body,
data: {
title: data.title,
body: data.body,
onClick: data.onClick || '',
},
tokens: to,
});
}
});
},
);
exports.sendPushNotificationToTopic = functions.https.onCall(
(data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called ' + 'while authenticated.',
);
}
admin.messaging().send({
data: {
title: data.title,
body: data.body,
onClick: data.onClick || '',
},
topic: data.topic,
});
},
);
Notifications handler
const initNative = useCallback(() => {
PushNotifications.register();
PushNotifications.requestPermission().then(result => {
if (result.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
const device = new DeviceUUID().get();
registerTokenToUser(device, token.value);
alert('Push registration success, token: ' + token.value);
},
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotification) => {
alert(JSON.stringify(notification));
// this array fires correctly with the app in foreground, but nothing on the notifications tray with the app in background if sent from my send functions, works correctly if sent from FCM
},
);
// Method called when tapping on a notification
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert(JSON.stringify(notification));
},
);
}, [PushNotifications, history, registerTokenToUser]);
Any suggestion?
Thanks
I've found the error myself,
for the notifications be visible in background mode the notification object needs to have "notification" key populated, that was missing in my case,
correct send function should be
exports.sendPushNotificationToUsers = functions.https.onCall(
(data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called ' + 'while authenticated.',
);
}
db.collection('users_meta')
.doc(data.to)
.collection('messagingTokens')
.get()
.then(messagingTokens => {
if (messagingTokens && messagingTokens.size) {
const to = messagingTokens.docs.map(i => i.data().token);
console.log(to); // I get to this console log and the tokens are printed correctly in an array
admin.messaging().sendMulticast({
title: data.title,
body: data.body,
notification: {
title: data.title,
body: data.body,
},
data: {
title: data.title,
body: data.body,
onClick: data.onClick || '',
},
tokens: to,
});
}
});
},
);
exports.sendPushNotificationToTopic = functions.https.onCall(
(data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called ' + 'while authenticated.',
);
}
admin.messaging().send({
notification: {
title: data.title,
body: data.body,
},
data: {
title: data.title,
body: data.body,
onClick: data.onClick || '',
},
topic: data.topic,
});
},
);

Get value returned form fetch assigned to a variable

I want to get the returned value "responseData" assigned to the data variable
fetch('http://localhost:8080/users/update, {
method: 'PUT',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
name:this.state.name,
Level:this.state.activity,
height:this.state.height,
weight:this.state.weight
})})
.then((response) => {
return response.json()
})
.then((responseData) => {
console.log(responseData)
this.setState({
data:responseData
})
}
);
I does return true I just want to get it assigned to the variable I already tried to use
this.setState({
data:responseData
})
But it didn't work
fetch('http://localhost:8080/users/update, {
method: 'PUT',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
name:this.state.name,
Level:this.state.activity,
height:this.state.height,
weight:this.state.weight
})})
.then((response) => {
return response.json()
})
.then((responseData) => {
console.log(responseData)
this.setState({
data:JSON.parse(responseData)
})
}
);
#Asad Thank you I figured it out it was my mistake though I tried to assign a json value to a string variable this is the correct code
this.setState({
data:JSON.parse(responseData)
})

How can I update my list when I type something in search?

search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
How can I use my search function to update my list whenever I enter something in my search box?
This is what I'm trying in my TextInput (SearchBox).
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor= {colors.whiteColor}
onChangeText={
name => {
this.setState({name});
this.search();
}
}
/>
Firstly responseJson is an actual json object, you don't need to stringify it and then parse it.
You could store the responseJson in the state
search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
Just make sure you set the initial state in your constructor of your component
constructor(props) {
super(props);
this.state = { data: [] }
}
Then you should be able to access your data by using this.state.data
Updated Answer to Updated Question
The problem is that you are not realising that setState is asynchronous. That is takes time for the state to update. That means that you are setting state and then hoping that the state will have updated by the time the next function is called. Unfortunately, calling setState in your TextInput is not having the desired effect.
I would update your search function to the following
search = (name) => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson, name: name});
})
.catch((error) => {
this.setState({name: name});
console.error(error);
});
}
Then in yourTextInput update your function call to
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor={colors.whiteColor}
onChangeText={ name => {
if (name.length > 0) {
this.search(name);
} else {
this.setState({data: [], name: ''});
}
}
}
/>
This will reduce the number of times setState is called.
uhm...
i'm not sure what 'body' part is for..
i mean the part
body: JSON.stringify({"name": this.state.name})
maybe is better like
body:[{'name':bla}] ?
anyway, try with this (and write 'Accept' header as a string):
(add the body part if is so important to you)
const fetchConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
fetch(strings.baseUri+"search_by_name",fetchConfig)
.then((response) => {
//use *return* statement to return a json object to THEN part
return JSON.parse(response)
})
.then((responseJson) => {
let jsonObj = responseJson;//responseJson is *already* a JSON object.
//you cannot alert a JSON data, it's will show as [object]
//you can do console.log() or
//console.warn() <--- this will showed on device in yellowbox, but i'm not sure about a json data.
})

Categories

Resources