Save the time stamp when the application goes into the background. Developed using React Native

REVISED: I am working on a React Native app where I need to keep track of the timestamp when the app goes into the background in order to determine if re-login is required. I am using async storage to store this timestamp on the device, utilizing the appstate functionality. However, for some reason, the getItem and setItem code is not executing. Any thoughts on why that might be?

componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState: any) => {

    if (
        this.state.appState.match(/inactive|background/) &&
        nextAppState === 'active'
    ) {
        this.getTime();
        this.checkTimeStamp();
        console.log(this.state.time, 'time var');
        console.log('app is active, and has been in the background');
    } else if (
        this.state.appState == 'active' &&
        nextAppState == 'active'
    ) {
        this.setTime();
        this.checkTimeStamp();
        console.log(this.state.time, 'time var');
        console.log('app is active, and just opened.');
    } else {
        this.setTime()
            //sets the timestamp
        console.log('app in background or closed');
    }
    this.setState({ appState: nextAppState });
};

async setTime() {
    let seconds = this.generateTime();
    try {
        const val = await AsyncStorage.setItem('time', seconds.toString());
        this.setState({ time: Number(val) });

    } catch (error) {
        console.error('onRejected function called: ' + error);
    }
}

async getTime() {
    let please = await AsyncStorage.getItem('time');
    this.setState({ time: Number(please) });
    console.log(this.state.time, 'time var');

}

Answer №1

For more information about monitoring AppState changes, visit the official React Native documentation at this link.

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

What is a way to retain the value of a variable after a request, while starting off with a different value on the initial load?

In my Flask application, users have the option to choose a specific time period with a start date and an end date. When the page initially loads, I want the start date to default to the first day of the current month and the end date to be the current day. ...

Updating dropdown menu choices in real-time

Here is how my signup form is structured: <input type="radio" value="a">a <input type="radio" value="b">b <select name="group"> <?php for ($i=1; $i<=4; $i++) { echo '<option value="'.$i.'">'.$i.&apos ...

Generate a nested array of objects by recursively looping through an array of objects

Imagine I have an array of objects structured like this: myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] I aim t ...

Retrieving form control values in AngularJS without using data binding

I recently implemented a form using rails scaffolding, which is functioning properly. However, I am now looking to enhance it by adding a new Angular controller. The purpose of this controller would be to calculate a score/progress bar that displays the pe ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Having trouble with the functionality of my API in Express and MariaDB

I have successfully implemented an API using MariaDB and ExpressJS with a functioning get route... const getAllBills = async (req, res) => { try { const conn = await pool.getConnection(); const result = await conn.query('SELECT ...

The function 'myfunc' was called within a render, however, it is not defined in the instance

I keep seeing this error message Property 'myfunc' was accessed during render but is not defined on instance, and I'm not sure why. Below are my HTML and JavaScript code snippets. const ListRenderingApp = { data() { return { todo ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Is it possible in Javascript to verify if a different script has been triggered?

I recently created a pop-out menu for a website using HTML and Javascript. The menu currently has a button that opens a div container with a close button inside it. While the buttons are functioning properly in hiding the div, the elements within the div d ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

Express.js throws an error when trying to access req.session when it

I've searched through multiple posts on this topic, however, none were able to resolve my issue. Below is the code snippet from my server.js file: var express = require('express'); var app = express(); app.configure(function(){ app.set ...

Organizing a collection of clothing sizes with a mix of different measurements using JavaScript

If I have an array like this: $arr = ['xl', 's', '1', '10', '3', 'xs', 'm', '3T', 'xxl', 'xxs', 'one size']; I aim to arrange the array in this o ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...

Manipulating Vue.js data within HREF attributes using PHP

Does anyone know how to successfully pass the data from Vue into PHP? I've attempted a few methods, but when I try to use the resulting link in the href attribute (href = $ where $ name), it shows a strange string instead of the expected URL from the ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

Angular tutorial: Loading Excel file with header located on row n

Is there an easy way to read specific columns from an excel file in Angular, starting from a certain row as the header? Most of the code I found involves complex scripts, and I'm looking for a simpler solution. Below is the code I've come up wit ...

React-router version 6 now supports breadcrumbs and partially matching routes

Currently, I am utilizing react-router-dom v6.8.1 (the most recent version at the moment) and had previously implemented a breadcrumb system that was functioning well with a third-party library called use-react-router-breadcrumbs. However, as per their doc ...

What is the best way to incorporate and utilize the JavaScript MediaWiki API in my projects?

I find it frustrating that the documentation for this library is lacking, making it difficult to figure out how to import it into my Typescript/React project. I am attempting to utilize the MediaWiki officially supported library but the examples provided ...

Guide on using jQuery to dynamically update a section of an ejs template following an AJAX request in ExpressJS

I'm currently struggling to figure out how to dynamically update a portion of the DOM using EJS after a jQuery ajax call. The issue arises with a live search feature that successfully sends a request to the server, searches the database, and returns a ...