'How to sync React native global data and stackNavigator?
I have a problem synchronizing the global variable with stackNavigator. In the given example, if I use the buttons from View everything works fine, but if I combine back arrow from header, then the value of the global variable is displayed as the value of the stored fragment, but the value of the global variable does not change. Pressing the Go to Details button again displays the unupdated value of the global variable increased by one. How to solve the problem that the value of a variable is synchronized with the state of the stackNavigator.
https://snack.expo.dev/@aleksandar_simin/task---global-and-stacknavigator
- Go to the detail screen 3 times
- back to the previous screen with the header back arrow
- then go to details again
- screen number will not be correct
Make it works correctly!
//------------------------------------
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
global.depth = 0;
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, marginTop: 150, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen {global.depth}</Text>
<Button
title="Go to Details"
onPress={() => {
global.depth += 1;
navigation.navigate('Details')}}
/>
</View>
);
}
function DetailsScreen({ navigation }) {
return (
<View style={{ flex: 1, marginTop: 150, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen {global.depth}</Text>
<Button
title="Go to Details... again"
onPress={() => {
global.depth += 1;
navigation.push('Details')}}
/>
<Button title="Go to Home" onPress={() => {
global.depth = 0;
navigation.navigate('Home');
}} />
<Button title="Go back" onPress={() => {
global.depth -= 1;
navigation.goBack()}} />
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Solution 1:[1]
function DetailsScreen({ navigation }) {
return (
<View style={{ flex: 1, marginTop: 150, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen {global.depth}</Text>
<Button
title="Go to Details... again"
onPress={() => {
global.depth += 1;
navigation.replace('Details')}}
/>
<Button title="Go to Home" onPress={() => {
global.depth = 0;
navigation.push('Home');
}} />
<Button title="Go back" onPress={() => {
global.depth -= 1;
navigation.goBack()}} />
</View>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chikabala |
