I have an app with two pages which both displaying a countdown. Each countdown when displayed starts with an value which was configured at the beginning. If the countdown who is currently displayed reaches zero the page with the other countdown gets displayed. It's supposed to go back and forth. I am able to switch between the two pages but I don't know how to reset the countdown. In my case the countdown reaches zero and does not start again when switching back and forth.
Page one
const Page1 = ({ navigation }) => {
return (
<View>
<CountDown
size={40}
until={someValueConfiguredAtTheBeginning}
timeToShow={["S"]}
onFinish={() => {
navigation.navigate("Page2");
}}
/>
</View>
);
};
Page two
const Page2 = ({ navigation }) => {
return (
<View>
<CountDown
size={40}
until={someValueConfiguredAtTheBeginning}
timeToShow={["S"]}
onFinish={() => {
navigation.navigate("Page1");
}}
/>
</View>
);
};
How can I modify the code that always when switching back and forth someValueConfiguredAtTheBeginning
gets used in the counter and not zero once the countdown has run down?
CodePudding user response:
You can use navigation listener to know when screen has been changed
const [SomeValueConfiguredAtTheBeginning, setSomeValueConfiguredAtTheBeginning] = useState(90)
useEffect(() => {
//create a listener everytime your screen is not focus and reset your countdown
navigation.addListener('blur', () => {
//here set your state to the original value;
SetSomeValueConfiguredAtTheBeginning(90);
});
return () =>{
//when component will unmounted remove the listener
navigation.removeListener('blur', () => {});
};
}, [navigation]);
CodePudding user response:
Solution
I just created an global state where I increase the stored variable on every onFinish
by one. Through the state update the whole component is rerendered.
const Page1 = ({ navigation }) => {
const [rerender, setRerender] = useContext(Renderer); /*init of global state*/
return (
<View>
<CountDown
size={40}
until={someValueConfiguredAtTheBeginning}
timeToShow={["S"]}
onFinish={() => {
navigation.navigate("Page2"); setRerender(rerender 1)
}} /*increase global state on every onFinish by one*/
/>
</View>
);
};
Page two
const Page2 = ({ navigation }) => {
return (
<View>
<CountDown
size={40}
until={someValueConfiguredAtTheBeginning}
timeToShow={["S"]}
onFinish={() => {
navigation.navigate("Page1");
}}
/>
</View>
);
};