How to remove the state value when screen is changed in react native - react-native

I am making an react native android app in which componentWillUnmount() does not works.Suppose user enters a text value in a text input in particular screen and goes to next screen.After that when user presses back button then i want that text value written in text input to be removed.I tries by adding this line in my code.
componentWillUnmount(){
this.setState({text:""})
}
Basically i was removing the state value which i put in TextInput.But this does not works.Same this is happening in case of activity indicator.When activity indicator start to fetch data then first i check if connected to internet or not.If not then by navigation i navigate to no network screen.But from there when i presses back button then activity indicator does not go away ? So how can i remove all the value of state in a component after navigating to different screen?

React Navigation allows you to add listeners so you track actions that are happening to the screen.
There are four listeners that you can add:
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition completed)
https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle
Here is an example of calling the willBlur, the others follow the same pattern you just change the value that is passed to the function.
componentDidMount () {
this.didBlurSubscription = this.props.navigation.addListener(
'didBlur',
payload => {
// you can perform actions here when the screen `willBlur`
this.setState({text: ''});
}
);
}
componentWillUnmount () {
// remember to unsubscribe
if (this.didBlurSubscription) {
this.didBlurSubscription.remove();
}
}
The reason your current solution is not working is that the screen isn't being unmounted it is going in and out of focus/blur. So the componentWillUnmount will not be called. Also if the component is being unmounted then you should not be trying to setState as that is an anitpattern and can lead to memory leaks.

Related

Which React navigation action to use to unmount

I have a react native app with two screens (actually too many): ScreenA and ScreenB. In ScreenA, I am doing some API calls and in ScreenB, I have some animation. I am using stack navigator to visit ScreenB from ScreenA. In ScreenB, I have some animation in my useEffect() hook and also from gestures. When I move away from ScreenB to ScreenA and then back to ScreenB, the state of the screen is not changed. It remains the same. I want the entire animation to reset, the useEffect() to be called again, but only for ScreenB. I want all my other mounted screens to be mounted, to avoid calling APIs and displaying data again but ScreenB to reset to its initial state if I move away from it. How can I achieve this in most efficient way possible? Thanks
You could use useIsFocused in a useEffect and reset the animation with something like
const isFocused = useIsFocused();
useEffect(()=>{
if(isFocused){
// start your animations
}
else{
// stop your animations
}
},[isFocused])

How to prevent user interaction during screen transition animation?

When navigating between screens using the StackNavigator with a fade transition, a user is able to click during the transition animation and possibly hit a TouchableOpacity on the screen that is being navigated away from. The TouchableOpacity registers the hit and thus the app responds accordingly. This is causing issues for "fast clicking" users where they click a button to navigate to a new screen and immediately click where they think a new button will be, but in reality is clicking a button on the previous screen.
Is there a way to prevent any user interaction during these transition animations? I have tried setting the transition duration to 0 like so:
transitionConfig: () => ({
transitionSpec: {
duration: 0
}
})
but the issue still occurs.
I do not want to disable the animation completely, because it is quick enough for most users and they like the animation.
So in your case you can do several things
You can use React Native Activity Indicator -> View
You can use Overlay Library -> react-native-loading-spinner-overlay -> View GitHub
If you like to make loading like facebook / instagram -> then use react-native-easy-content-loader -> View GitHub
you need to flag screen before navigating away; disabling all touchs.
an easy way would be to have a reusable hook that return a transparent absolute positioned View that cover entier page and a callback to enable it;
so you flow will be; enable this which will overlap whole screen and capture any clicks basically disabling them;
something more like:
function useOverlay(){
const [isVisible, toggle] = React.useState(false);
const Component = React.memo(()=><View style={styles.transparentAbsolute} />,[])
return [toggle, isVisible ? Component : null];
}
then inside your Screen before you call navigate just call toggle
and include Component at top of you screen;
export default function TabOneScreen({ navigation }: RootTabScreenProps<'TabOne'>) {
const [ toggle, component ] = useOverlay();
return (
<View style={styles.container}>
{component}
<Button onPress={()=>{toggle(true); navigation.navigate('Home');} title="go home" />
</View>
);
}

react native while come back to previous screen the page data is not updated

I did some changes in my second screen and comeback to my first screen the data is not updated. After reloading app the data is updated. How to update the data from second screen to first screen navigation without refresh or reload
What i believe without any code is that if you do navigation.goBack() or navigation.navigate() it doesnt call the api if its in your componentDidMount, what you can try is adding an eventlistener called onFocus so that whenever screen is focused you call that :
like this in your componentDidMount
componentDidMount(){
this.focusListener = this.props.navigation.addListener('didFocus', () => {
// The screen is focused
// Calling action to reset current day index to 1
this.getItineryData();
});
}
Hope it helps

React-native / redux - how to re-initialize screen via navigation?

I'm developing a react-native / redux app with a bottom-tab-navigator similar to the example at https://reactnavigation.org/docs/en/tab-based-navigation.html#customizing-the-appearance. My screens all connect to a Redux store and display shared data, however I'd like at least one of these screens to ignore the current data in the store and instead re-initialize this data each time it's navigated to (instead of continuing to display the data in whatever state it was last left in).
The screen has a method to do this, but I can't figure out how to call it after the first time the screen is rendered (e.g. from the constructor or componentDidMount() method). I can't call it from the render() method as this causes a "Cannot update during an existing state transition" error.
I need my navigator to somehow cause my HomeScreen.initializeData() method to be invoked each time the Home icon is pressed, but how do I do this?
HomeScreen.js:
initializeData() {
this.props.resetData(initialValue);
}
const initialValue = ...
(resetData() is a dispatch function that re-initializes the Redux store).
Updating state from render() would create an infinite loop. Also, you don’t want to run your state update every time the component re-render, only when the tab button is pressed. This tells me that the proper place to make your state update is some onPress function on the tab button.
So the question now relies on how to implement some onPress function on a tab button. I believe this answer this question:
Is there an onPress for TabNavigator tab in react-navigation?
So I found an answer, it's a little more complicated than might be expected: As Vinicius has pointed out I need to use the tabBarOnPress navigation option, but I also need to make my dispatch function available to this navigation option.
To do this I found I need to pass a reference to my dispatch function (which is available as a property of my screen) into the navigation option, so I've used navigation params to do this and here's what I've ended up with:
HomeScreen.js:
componentDidMount() {
initializeData(this.props);
this.props.navigation.setParams({ homeProps: this.props });
}
export const initializeData = (homeProps) => {
homeProps.resetData(initialValue);
};
const initialValue = ...
AppNavigator.js:
tabBarOnPress: ({navigation, defaultHandler}) => {
const routeName = navigation.state.routeName;
if (navigation.state.params === undefined) {
// no params available
} else if (routeName === 'Home') {
let homeProps = navigation.getParam('homeProps', null);
initializeData(homeProps);
} else if (routeName === ...
...
}
defaultHandler();
}
Notes:
I'm passing props as a navigation param rather than my dispatch function (which also works) as it's more flexible (e.g. it makes all of my dispatch functions available).
initializeData() is called both during construction of HomeScreen (for the first time the screen is displayed) and from the navigation icon (for subsequent displays of the screen).
It's necessary to check that params is defined within the navigation option as it'll be undefined the first time the screen is displayed (as screen construction has yet to occur). This also makes it necessary to call initializeData() during screen construction.

I am using Backhander in react native with react-native-router-flux but its reacting on all screens where I want to make it work for screen specific

I am using Backhander in react native with react-native-router-flux but it's reacting on all screens where I want to make it work for screen-specific, but when I am trying to get the current route name in the onBackPress method, it's giving me first screen name in router name.
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress = () => {
alert(this.props.navigation.state.routeName)
}
First of all - BackHandlers in React Native are global and not screen specific. But you can achieve your wanted behavior.
Some background
With BackHandler.addEventListener you push an event listener on a Stack of event listeners, with BackHandler.removeEventListener you remove the given listener from the Stack. When the BackButton is pressed, the top listener from the stack is called and the code is executed. Then the next listener is called and so on. This stops when the first listener returns true.
For your specific problem
You should ensure that you add an event listener on the page you want it to (like you are doing in your code example)
You should ensure that your event listener returns true
You should ensure that your listener gets removed when unmounting the view (like you do)
Now you BackHandler should work for the view you have implemented it in (lets call it view1). But you have to think about all the other views. Especially when you are pushing views on top of view1. Ether you can implement an "onFocus" and "onBlur" method for view1 and use this methods instead of componentDidMount and componentWillUnmount for adding and removing event listeners, or you have to add event listeners for the back handler for all views that are pushed on top of view1.
Hope that helps :-)
Source: https://facebook.github.io/react-native/docs/backhandler
If you want backHandler to act differently for specific screen then you can use Actions.currentScene in your onBackPress function :
onBackPress = () => {
if(Actions.currentScene === 'SceneKey'){
return true;
}
Actions.pop();
return true;
}