What is the best way to utilize and modify global variables within a React Native environment?

I am a beginner in the world of react-native and recently created a stop watch. However, I encountered an issue where the stop watch stops working when I navigate to another page and then return. My goal is to have the stop watch continue running until the user presses the stop button. I believe using a global variable might solve this problem, but I am unsure how to implement it. Below is my current code:

export default class Record extends Component {
 constructor(props) {
  super(props);
  this.state = {
  stopwatchStart: false,
  stopWatchTime: '00:00:00'

};
toggleStopwatch() {

if (!this.state.stopwatchStart) {
  startDate = new Date();
  startTime = startDate.getTime();
  that = this;
  setInterval(function () {
    var date = new Date();
    time = (date.getTime() - startTime) / 1000;
    hour = parseInt(time / 3600);
    timeAgo = parseInt(time % 3600);
    min = parseInt(timeAgo / 60);
    second = parseInt(timeAgo % 60);
    that.setState({
      stopWatchTime: (hour + ':' + min + ':' + second)
    })
  }, 1000);  
}
this.setState({ stopwatchStart: !this.state.stopwatchStart });}

Answer №2

I'm seeking clarification on your specific needs. Would you like the interval to continue running even after changing screens? It's important to note that components do not typically function in this way. To properly manage the lifecycle of components, it is recommended to refer to the documentation at https://reactjs.org/docs/react-component.html. This means that when you change screens within the "Record" component, it will be unmounted and the interval will consequently be destroyed. If you could provide more details about how you intend to use the interval, especially if you plan to utilize it across multiple components, it would greatly assist in providing a suitable solution.

Answer №3

It's still unclear to me what you mean by "view", but it could be related to switching to another app or putting the current app in the background. To ensure data persistence in your React Native application, consider utilizing AsyncStorage. In the future, you may explore options like Sqlite, Redux Persist, or similar solutions to maintain persistent data.

You can save data before the app is sent to the background using the following code:

try {
  await AsyncStorage.setItem('timeKey', myTimeVar.toString());
} catch (error) {
  // Handle error saving data
}

To retrieve the most recent value using the respective key, use this code snippet:

try {
  const value = await AsyncStorage.getItem('timeKey');
  if (value !== null){
    console.log(value);
  }
} catch (error) {
  // Handle error retrieving data
}

You don't necessarily need to run a timer in the background; instead, you can calculate the difference between when the app was closed and the current time plus any time wasted during the first session to achieve your desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for making a dynamic active button using javascript

I'm trying to create a toggle button with eight buttons. When seven out of the toggle buttons are clicked, it should toggle between two classes and change its CSS styles. If the daily button is clicked, it should toggle the styles of the other seven b ...

Using the key from the parent ng-repeat to filter ng-repeat

Here is an example: <div class="row" ng-repeat="(key, value) in sections"> <h5>{{ value }}</h5> <ul> <li ng-repeat="item in $parent.items | filter: key">{{ item.name }} -- {{ item.section }}</li> < ...

Iterate through several table data cells, extract various data points, and populate an array

I am facing a challenge with two tables on my webpage. The second table is dynamically populated with HTML using JavaScript. To accomplish this, I am checking if the <tr> tags inside the tbody are empty by using the following code: var rowCount = $( ...

eliminate a mesh from the view following a mouse hover event triggered by a raycaster

            When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using INTERSECTED.material.color.setHex(radioHoverColor); and reset it ...

Customizing CSS to differentiate the color of active card headers in a Bootstrap accordion

I currently have a basic bootstrap accordion set up, as shown below. My goal is to style the .card-header element of only the expanded .card section without impacting the other .card-header elements. Is there a way to specifically target the expanded ite ...

Using innerHTML to replaceAll also modifies characters within the tags

I created a custom function to emphasize specific strings within a text by surrounding them with span tags and updating the content using the innerHTML property of the targeted element. However, I encountered an issue while working with innerHTML instead ...

Receiving a redirect when making an AJAX post request in ASP.NET

I am currently working with the Visual Studio 2013 ASP.NET Identity template. Once a user logs in successfully, they are directed to a page containing a table. This page includes search options that are powered by JavaScript. The JavaScript function sends ...

Tips for inserting a gap between text and underline on android devices

I have set the text of a textview as - <string name="text"><u>this is my text</u></string> There should be some space between the text and the underline, so I included lineSpacingExtra="2dp" in the textview attributes. However, i ...

Utilizing SVG elements for interactive tooltips

Can the < use > element show the rect tooltip on mouseover in modern browsers? Refer to 15.2.1 The hint element. <svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol i ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Utilizing Jquery to Load JSON Arrays as Tooltip Messages

I have successfully loaded the descriptions of my JSON variable into my script as tooltips. However, I am encountering two issues: When hovering over one sentence in my table, tooltips for all four sentences appear. It seems like I am unable to revert my ...

Encountering an Uncaught TypeError in Reactjs: The property 'groupsData' of null is not readable

While working on a ReactJs component, I encountered an issue with two basic ajax calls to different APIs. Even though I am sure that the URLs are functioning and returning data, I keep getting the following error message: Uncaught TypeError: Cannot read p ...

Removing an Element According to Screen Size: A Step-by-Step Guide

Currently, I am facing a dilemma with two forms that need to share the same IDs. One form is designed for mobile viewing while the other is for all other devices. Despite using media queries and display: none to toggle their visibility, both forms are stil ...

How can I incorporate a JavaScript module into my Typescript code when importing from Typeings?

Exploring Angular2 and Typescript with the help of mgechev's angular2-seed for a new project has been an interesting experience. However, I have encountered a problem along the way. My intention is to incorporate Numeral into a component, and here ar ...

The age calculator is failing to display the accurate age calculation

This code is designed to compute the age based on the selected value in the combo box, and display the result in the text box below. The age should update every time the user changes the selected value in the combo box. However, the computed age is not cur ...

The error message "Unexpected token var Node.js" means that there is a syntax error

Currently, I am dealing with Node.js and attempting to present a chart that is created from coordinates in a txt file uploaded to the server. However, I am facing an issue where everything works perfectly when I upload the file on the web page except for t ...

Obtaining csv gzip content as a csv file from a remote location without the need to save the file locally

Assuming I am downloading a file named 'abc.csv.gz' from an FTP server, my goal is to access the content of this file as a CSV remotely without saving it locally. The code snippet below allows me to retrieve the content of a CSV file, but it fai ...

What significance does the dollar sign hold within node Modules?

I've been researching online but I can't seem to find any concrete information. Can someone explain the purpose of the '$' symbol in node modules? For instance, in this code snippet, it's being used extensively: Dashboard Control ...

In order to keep a div fixed at the top of the screen as you scroll, you can achieve this effect by utilizing CSS positioning. As the user scrolls down the page, the div

Can someone please help me figure out how to make a div element stay fixed on the screen as I scroll down the page? I've tried multiple solutions but nothing seems to be working. Any assistance would be greatly appreciated! I'm struggling with t ...

What could be the reason for the non-functioning onclick event on both Android and iPhone devices?

Utilizing the Prototype JavaScript library, I have been able to successfully create dynamic drop-down menus. However, I am facing an issue with event handling on mobile devices such as Android and iPhone browsers. Before the page loads, there are no event ...