So i have a react native app building with expo and i have enabled push notifications .when i click on notification i want to redirect the user to chatScreen.however, the problem is that when app is running and i receive a notification the user is redirected successfully but when the app is closed and i click on notification the app opens but user is not redirected to chat screen .below is the code .
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
// Define the background task
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
async ({ data, error, executionInfo }) => {
console.log("here");
if (error) {
console.log("Error in background task:", error);
return;
}
NewNavigate.navigate("ChatScreen", {
nexists: true,
});
}
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
Alert.alert("You Must Enable Notifications For Updates.");
return;
}
Notifications.getDevicePushTokenAsync;
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
} else {
Alert.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",
});
}
return token;
}
const Home = (props) => {
const Stack = createNativeStackNavigator();
const [showAboutScreen, setShowAboutScreen] = useState();
const [isConnected, setisConnected] = useState();
const uctx = useContext(Userctx);
const [expoPushToken, setExpoPushToken] = useState("");
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
const { navigate } = useNavigation();
// useEffect(() => {
// registerBackgroundTask();
// }, []);
// const registerBackgroundTask = async () => {
// // Check if the background task is already registered
// const isRegistered = await TaskManager.isTaskRegisteredAsync(
// BACKGROUND_NOTIFICATION_TASK
// );
// console.log("registered", isRegistered);
// if (!isRegistered) {
// await Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
// }
// };
useEffect(() => {
registerForPushNotificationsAsync()
.then((token) => {
setExpoPushToken(token);
return AsyncStorage.setItem("DeviceToken", token);
})
.then((i) => console.log("Token Done", i))
.catch((e) => console.log("token Error", e));
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
navigate("ChatScreen", {
nexists: response.notification.request.identifier,
});
});
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
useEffect(() => {
const checkInternetConnection = async () => {
const netInfoState = await NetInfo.fetch();
setisConnected(netInfoState.isConnected);
};
const unsubscribe = NetInfo.addEventListener((state) => {
setisConnected(state.isConnected);
});
checkInternetConnection();
// Clean up the event listener when the component unmounts
return () => {
unsubscribe();
};
}, []);
// useLayoutEffect(() => {
// AsyncStorage.removeItem("aboutScreenShown", () => {
// console.log("removed");
// setShowAboutScreen(true);
// });
// AsyncStorage.removeItem("user", () => {
// console.log("removed user");
// });
// AsyncStorage.removeItem("DeviceToken", () => {
// console.log("removed token");
// });
// }, []);
useLayoutEffect(() => {
AsyncStorage.getItem("user")
.then((value) => {
if (value === null) {
} else {
const data = JSON.parse(value);
uctx.setuserInfo(data);
}
})
.catch((error) => {
console.log("Error retrieving local storage value:", error);
});
}, []);
useEffect(() => {
// Check local storage value to determine if the "About" screen has been shown before
AsyncStorage.getItem("aboutScreenShown")
.then((value) => {
console.log("first Time View", value);
if (value === null) {
// If the value is null, it means the "About" screen has not been shown before
setShowAboutScreen(true);
// Update local storage value to indicate that the "About" screen has been shown
AsyncStorage.setItem("aboutScreenShown", "true");
} else {
console.log("Available");
setShowAboutScreen(false);
}
})
.catch((error) => {
console.log("Error retrieving local storage value:", error);
});
}, []);
if (!isConnected)
return (
...
);
it doesnt matter even if i register the task inside the useEffect ,nothing happens .Any help will be appreciated .