I am creating an app that has 3 main pages using react-native navigation:
Homescreen, Historikk, and Kjøring
The screen named Homescreen is the Bottom stack and the others are stacked ontop.
In my page called "Kjøring" I have a button that functions as a start and stop button, using a conditional to decide what is displayed for the user, and what onClick function should be used.
<View>
{!start?
//START KNAPP
<View style={styles.startContainer}>
<TouchableOpacity onPress={handleStart} style={styles.startButton}>
<Image style={styles.playImage} source={require("../Images/Play.png")} />
</TouchableOpacity>
<Text style={styles.startContainerText}>Start</Text>
</View>
:
//STOPP KNAPP
<View style={styles.startContainer}>
<TouchableOpacity onPress={handleStop} style={styles.startButton}>
<Image style={styles.playImage} source={require("../Images/Stop.png")} />
</TouchableOpacity>
<Text style={styles.startContainerText}>Stopp</Text>
</View>
}
</View>
My problem is that when i press the start button and navigate back to the bottom stack ( Homescreen ), and then back to the page: "Kjøring". The button is displaying the Start button, instead of the Stop button because my state has been reset.
I then tried to create the state in the Homescreen and send the state to the "Kjøring" screen, and I could send the current state from the Homescreen to the "Kjøring" screen using:
const [started, setStarted] = useState(true);
onPress={() => {navigation.navigate("Kjøring",{started: started})}}
I could have tried sending the current state the same way, but i am using the default header and back button of react-native stack navigation v6, so i have no way to send it with when i go back without recreating the header.
I cannot find out how to send the setState function to the "Kjøring" screen.
I have tried:
- Creating a function and sending it as a prop like i did with the started state
- Passing the setState itself through as a prop
- Passing an arrow function that sets changes it
CodePudding user response:
I think DeviceEventEmitter should work in your case
in Home Page add a listener
useEffect(() => {
DeviceEventEmitter.addListener('event.testEvent', eventData => {//action that need to be performed});
return () => {}; }, []);
In the Page where the event happens emit the following code:
DeviceEventEmitter.emit('event.testEvent', true);
Also remove the listener on exiting the Page by adding the below code:
useEffect(() => {
return () => {
DeviceEventEmitter.removeAllListeners('event.testEvent');
};
}, []);
