In my react native app, when I click on a notification I navigate to a chat screen, in that chat screen I have a useEffect that fetches the chat messages, problem is, if chat screen was the last opened screen before closing the app, the useEffect doesn’t fire.
Funny thing is, I tried to use isFocused but it’s not firing either!
Any idea how I can handle this?
useEffect(() =>
{
Alert.alert('FETCHING');
}, []);
useEffect(() => {
if(isFocused)
{
Alert.alert('FETCHING');
}
}, [isFocused]);
Is this the default bhaviour when navigating to a screen after clicking on a notification?
import { navigationRef, isReadyRef, navigate } from '@env/RootNavigation.js';
handleBackgroundNotificationClicked(data)
{
let notifData = JSON.parse(data.data.data);
this.initChat(notifData.chat,false);
navigate('ChatList', { chatId : notifData.chat.id });
}
2
Answers
I write my opinion below.
It seems like you are facing an issue where the useEffect hook is not firing when navigating to the chat screen after clicking on a notification. Additionally, you mentioned that using the isFocused state variable also does not work.
One possible reason for this behavior could be that the chat screen is already mounted when the notification is received, so the useEffect hook doesn’t trigger again. To overcome this, you can try using the navigation events provided by React Navigation.
First, make sure you have access to the navigation object in your component. You can achieve this by using the useNavigation hook from the @react-navigation/native package.
In this code snippet, I used the addListener method provided by the navigation object to listen for the ‘focus’ event. Whenever the chat screen gains focus, the callback function inside the listener will be executed, allowing you to fetch the chat messages.
Make sure to return the unsubscribe function from the useEffect hook to remove the listener when the component unmounts.
By using this approach, the useEffect hook will trigger every time the chat screen gains focus, regardless of whether it was the last opened screen before closing the app or not.
I hope this helps you resolve the issue with the useEffect hook problem.
Let me know if you have any further questions!
David.
You can use the useFocusEffect that is built into react-navigation like this
It will trigger every time the screen is opened