How can you automatically show the current time upon entering a page using React Native?

Is there a way to automatically display the current time when a user enters the page? I currently have code that only shows the current time when the TouchableOpacity is pressed, but I want it to update automatically as soon as the user arrives on the NetuneyDigum page.

function NetuneyDigum() {
  const navigation = useNavigation();
  const [currentTime, setCurrentTime] = useState('');
  const [isSelected, setSelection] = useState(false);
  const [selectedValue, setSelectedValue] = useState('1');

  return (
    <>
      <KeyboardAwareScrollView
        style={{ flex: 1, backgroundColor: '#cbced4', marginBottom: 50 }}
      >
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            backgroundColor: '#cbced4',
          }}
        >
          <View
            style={{
              paddingTop: 30,
              flexDirection: 'row',
              paddingRight: 180,
            }}
          >
            <View
              style={{
                flexDirection: 'row',

                alignItems: 'center',
                justifyContent: 'center',
                left: 58,
              }}
            >
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 18,
                  color: 'black',
                }}
              >
                Current Time:
              </Text>
            </View>
            <View
              style={{
                width: 150,
                borderRadius: 5,
                borderColor: 'black',
                borderWidth: 2,
                left: 80,
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: 'white',
              }}
            >
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 20,
                  color: 'black',
                }}
              >
                {currentTime}
              </Text>
            </View>
            <TouchableOpacity
              onPress={() => {
                const time = moment().format('HH:mm');
                setCurrentTime(time);
              }}
              style={{
                height: 60,
                width: 60,
                borderRadius: 5,
                borderColor: 'black',
                borderWidth: 2,
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#275d9f',
                left: 100,
              }}
            >
              <Icon size={40} color="white" name="time-outline" />
            </TouchableOpacity>
          </View>

Answer №1

Give this method a shot

// Works just like componentDidMount and componentDidUpdate:
  useEffect(() => {
    const time = moment().format('HH:mm');
    updateTime(time);
  });

Answer №2

This code snippet demonstrates how to use the functionality effortlessly. Once implemented, you have the flexibility to modify the time display as needed.

const [initialTime, setInitialTime] = useState(new Date());

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

The HTTP request is malfunctioning in a different location

I'm facing an issue where my code works in the w3schools code editor, but not on localhost or cpanel host. When I try to run it on another host, it gives me a bad request and doesn't return the answer. Here is the code snippet that I am working ...

Dynamic animations with RaphaelJS - Creating animated connections

I recently came across a similar project here: My current project involves animating boxes by clicking a button. While I am able to move the boxes around smoothly during animation, the issue is that the connections between them do not move along. Is there ...

Dealing with unresponsive sidenav in MaterializeCSS when trying to click and pop-out with React

One particular challenge I am encountering relates to user experience when it comes to authentication. If a user is authenticated, the AuthLinks will be displayed, but if not, the GuestLinks will show instead. The issue arises when switching to responsive ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Customize Metadata Efficiently with NextJS 13 - Eliminate Redundant Requests

Imagine you have a server-side component located in the app directory called page.js, which represents a person: export default async function Person({ params }) { const person = await getPerson(params.id); return ( <h1> {person. ...

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Issue with PLUploader in ASP.Net/JQuery: "Add Files" button not functioning post image upload操作

Hello, I've been utilizing the PLUploader controller for ASP.NET in C#. Initially, it works as intended, but after uploading files, the "add files" button becomes disabled or stops working, preventing me from adding more images. Can anyone offer assi ...

Dynamic color change in SVG

I am facing an issue with changing the color of svg images in a menu list using the filter CSS property. Even though I have obtained the correct filter value from a library that converts hex to CSS filter, React seems unable to set this property on the ima ...

avoid selecting a d3 table

I'm currently learning about creating tables in D3 and I have a question regarding when to use ".select()": For example, when constructing circles: var circles = svg.selectAll("circle") .data(dataSet) .enter() .append("circle") .att ...

Creating various containers in React JS for different components

I am faced with the task of rendering multiple DOM elements from my JavaScript code. Imagine I have div elements like this: <div id="div1"><div> //Some Html tags <div id="div2"><div> //Some Html tags <div id="div3" ...

Display a component by selecting a hyperlink in React

Currently working on a story in my storytelling, which might not be too important for the question I have. What I am trying to accomplish is creating a scenario where there is an anchor tag that, once clicked, triggers the opening of a dialog box or modal ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

Can anyone explain to me how to render attributes of a tag in Vue? I'm curious about how v-for interacts with HTML

<ul> <span class="tabs" :class="{ activeTab: selectedTab === tab }" v-for="(tab, index) in tabs" @click="selectedTab = tab" :key="tab"> {{ in ...

Prevent unnecessary image resizing during parallax scrolling animation

Check out my demonstration where the image scaling results in the margin-top of the parallax wrapper being unable to dynamically adjust. Demonstration: http://jsfiddle.net/KsdeX/12/ .wrapper-parallax { margin-top: 150px; margin-bottom: 60px; } W ...

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

Unleashing the Power: Crafting Impeccable For Loops

After running the select query in the "get-employee.php" page, I obtained the answer for this page. Then, I returned the data to the previous page (home.php). On this page, I added a for loop in JavaScript before the tag with the class "col-md-3". Within t ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...