Not receiving userText (response from textInput) in expo notification response

I'm pretty new to expo and expo notifications. Currently, I'm working on a project where I need the user to be able to send a response to a notification. From what I understand, I should be able to do this by creating a textInput in the notification category actions:

 Notifications.setNotificationCategoryAsync('notification', [
    {identifier: 'respond', 
    buttonTitle: 'Respond',
    textInput: {
      placeholder: "Please respond, 
      submitButtonTitle: "Send",
     },
    },
  ],)

and then I should get the response in my console.log():

const handleNotificationResponse = async(
    response: Notifications.NotificationResponse,
  ) => {
    if (response) {
      console.log(response.userText)
}
}

However, I'm getting undefined for console.log(response.userText), and when I console.log(response) it doesn't show userText. It does show actionIdentifier, which is equal to my identifier, respond. Does anyone know why this could be happening? I would really appreciate any help or guidance. Thank you!

index.tsx

...
const prefix = Linking.createURL("");
const linking = {
  prefixes: [prefix],
  config: {
    screens: {
    },
  },
};


export default function Navigation() {
  return (
    <NavigationContainer
      linking={linking}>
      <RootNavigator />
    </NavigationContainer>
  );
}

const Stack = createStackNavigator<RootStackParamList>();

function RootNavigator() {
const { navigate } = useNavigation<StackNavigationProp<RootStackParamList>>()
const {registerForPushNotificationsAsync, handleNotificationResponse} =
 useNotifications()

  useEffect(() => {
    registerForPushNotificationsAsync();
    Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: true,
        shouldSetBadge: true,
      }),
    });

    const responseListener =
      Notifications.addNotificationResponseReceivedListener(
        handleNotificationResponse
      );

    return () => {
      if (responseListener)
        Notifications.removeNotificationSubscription(responseListener);
    };
  }, []);
...

useNavigation.tsx

import react,{ useEffect } from "react";
import { Alert, Linking, Platform } from "react-native";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useMutation, gql } from '@apollo/client';
import { responsePathAsArray } from "graphql";


const REGISTER_DEVICE_MUTATION = gql`
mutation registerDevice($input: DeviceRegisterInput!) { 
   registerDevice(input: $input) 
  
}
`;

const UNREGISTER_DEVICE_MUTATION = gql`
mutation unregisterDevice($token: NEString!) { 
    unregisterDevice(token: $token) {
    token
  }
}
`;

export const useNotifications = /*async*/() => {
  const { navigate } = useNavigation<StackNavigationProp<RootStackParamList>>()
  const [registerDevice, { data: registerDeviceData, error, loading }] = useMutation(REGISTER_DEVICE_MUTATION);
  const [unregisterDevice, { data: unregisterDeviceData, error:unregisterDeviceError, loading:unregisterDeviceLoading }] = useMutation(UNREGISTER_DEVICE_MUTATION);
  console.log(error instanceof Error);
  console.log(JSON.stringify(error, null, 2));
  const registerForPushNotificationsAsync = async (alertUser?: boolean) => {
    const user= await AsyncStorage.getItem('user');
    try {
    if (Device.isDevice) {
      if (!user) return; 
      const { status: existingStatus } = await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== "granted") {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }

      if (finalStatus !== "granted") {
        if (alertUser) {
          Alert.alert(
            "Error",
            "To enable Push Notifications please change your settings.",
            [
              {
                text: "OK",
              },
              {
                text: "Open Settings",
                onPress: openSettings,
              },
            ]
          );
        }
      }
      const token = (await Notifications.getExpoPushTokenAsync()).data;
      const previousToken = await AsyncStorage.getItem('PushToken');
      if (previousToken && previousToken === token) {
        return console.log('Push Token exist');
      }
  
      if (previousToken && previousToken !== token) {
        await unregisterDevice({variables: { token: previousToken } });
  
        console.log('Push Token update');
      }

     
      registerDevice({variables:{
        input:{ 
          userId: user,
          token: token, 
        },
        }});
      if (registerDeviceData?.registerDevice) {
        AsyncStorage.setItem('PushToken', token);                 
      }
      else {
        throw new Error("User doesn't allow for notifications");
      }
    } else {
      alert("Must use physical device for Push Notifications");
    }

    if (Platform.OS === "android") {
      Notifications.setNotificationChannelAsync("default", {
        name: "default",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    }
  }
  catch(error) {
    console.log('error register device', error);
  }
  };


 
  const handleNotification = (notification: Notifications.Notification) => {
    console.log('notification', notification)
  };

Notifications.setNotificationCategoryAsync('notification', [
    {identifier: 'respond', 
    buttonTitle: 'Respond',
    textInput: {
      placeholder: "Please respond, 
      submitButtonTitle: "Send",
     },
    },
  ],)

const handleNotificationResponse = async(
    response: Notifications.NotificationResponse,
  ) => {
    if (response) {
      console.log('response', response)
      console.log(response.userText)
    const data: { url?: string } = response.notification.request.content.data;

  };

  return {
    registerForPushNotificationsAsync,
    handleNotification,
    handleNotificationResponse,
  };
};




Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations