I'm confused as to why the ID value is showing up as Undefined in the code snippet for React

Why do I keep getting 'undefined' when trying to console the id even though it should be in scope?

function App() {
  let id;

  let [time, settime] = useState('');

  function timechnage() {

    id = setInterval(() => {
      settime(Date);
    }, 1000);

  }


  function timecage() {
    console.log(id);

    console.log(id);

    settime(0);
  }

  return (

    <div>
      <p>Time is {time}</p>
      <button onClick={timechnage}>Start</button>
      <button onClick={timecage}>Reset</button> 
    </div>
  )
}

export default App;

Answer №1

id is constantly reset whenever the component updates, causing its previous value to be erased.

If you want to maintain the value of id throughout the lifespan of your component, you should store it in a ref:

// Initialize the ref
const id = useRef();

// Set the value
id.current = setInterval(...

// Retrieve and display it
console.log(id.current)

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 the best way to pass props in React?

Develop the App2.js component and integrate it into App.js. Utilize s3 as props z1 within App2. Transfer it to a page in App2 as props. How should I handle passing props z1? static getDerivedStateFromProps(props, state) { return { z1: props.s3 } } ...

I'm having trouble getting this text to align properly next to the image. Plus, I can't seem to achieve a horizontal screen alignment either

There seems to be an answer available, but I'm clearly not understanding it, so I've come here seeking further explanation and assistance. CSS can be quite complex, right? Here's a screenshot of my current project: https://i.stack.imgur.com/ ...

Displaying and concealing a component using onClick in React with Material UI

I want to create a functionality where the Material UI Box component opens when clicking on a Button and closes when clicking on the Button again. I have searched for solutions on Google but couldn't find anything straightforward. I am looking for a s ...

Issue with the Edit feature causing conflicts with the local storage and generating error messages

There seems to be an issue with my edit function that is causing it to override the local storage when I attempt to save and interfering with my delete function as well. I have searched through similar posts for a solution but have not been able to pinpo ...

Preventing Cross-Origin Resource Sharing for Dockerized React project's API request

I am encountering challenges while trying to run a detached dockerized React application that is making Restful calls to a dockerized Node.js microservice. The main issue I am facing is that the requests are being blocked by the CORS policy, showing the fo ...

jQuery not being applied to dynamically added dropdown element

I am currently utilizing bootstrap and jquery within my react project. I have a button that, when clicked, should transform into a dropdown field. The dropdown functions properly when placed statically, but the functionality is lost once it is dynamically ...

Struggling to modify the datetimepicker material-ui within a react js class component

I am currently using a datetimepicker component from material-ui/pickers in a class-based react-js component. I am facing an issue where the datetimepicker closes immediately every time I click on any part of it (date, year, etc.). Here's a snippet of ...

Encountering an issue with locating 'react-firebase-hooks'

I've been working on a project using Next.js and recently added the package called react-firebase-hooks to it. Here is an excerpt from my Package.json file: { "name": "whatsapp", "version": "0.1.0", " ...

"Effortlessly incorporate a new contact with Material UI's latest simple dialog

I've been exploring the material-ui next branch and using a specific example as a guide to create a dialog. For more information, you can check out the example here: You can also view the code sandbox here: https://codesandbox.io/s/7rq8nl11x I&apos ...

Adding custom validations for React Material UI controls is a breeze with these simple steps

My ReactJs application requires validation on all fields, such as name, phone number, email, password, and confirm password. Validation messages should be displayed when invalid data is entered in these fields. import React from 'react'; imp ...

Navigating with NextJS router is pushing a strange link to the

https://i.stack.imgur.com/wL0gx.jpg Whenever I attempt to redirect to the home page after logging in, or redirect to the login page when trying to access a page without proper tokens, the URL becomes distorted. Is there a way to prevent this distortion a ...

Utilize a Material UI GridList to transform images into a captivating background display

Incorporating a GridList displaying a variety of images fetched from an external source, I have successfully created an ever-changing image gallery. Now, my goal is to convert this dynamic image gallery into grayscale or transparency and utilize it as a ba ...

Enhance user experience by customizing login functionalities in Meteor using React: Integrate personalized

Currently, I am utilizing account-ui to incorporate a drop-down login feature in Meteor. However, I have encountered an issue where I am unable to expand user sign-up functionality to include First and Last Name fields. This is because Meteor account ui on ...

Fetch data asynchronously prior to loading the DOM

Currently in the learning process and facing a hurdle concerning how to retrieve data from an async function and display it in the DOM. The issue I'm encountering is that I am receiving 'undefined' as the DOM gets rendered before the async ...

What are some methods for applying border styles to the first and last row of a table using Material UI?

In my current project, I am utilizing the combination of Material UI and React Table. Recently, I was asked to implement an expandable row feature, which I successfully added. Once the user expands the row, we need to display additional table rows based on ...

Error: Incorrect data type found in React Route component

I've encountered an issue while attempting to utilize the Route component in my application. The error message I'm receiving reads as follows: [ts] Type '{ path: "/:shortname"; component: typeof FirstComponent; }' is not assignable ...

What are some ways to add border styles to the Material UI TableRow Component?

In my project, I am utilizing the Table component from Material UI. I have been trying to apply border styles to the TableRow Component using scss classNames for styling purposes. Usually, the border styling is applied in the TableCell, but this doesn&apos ...

Ensure that ExpansionPanel remains expanded while printing

Currently, I am utilizing an ExpansionPanel in my project where the state of expansion is controlled based on certain conditions. However, I have a requirement for the ExpansionPanel to remain expanded at all times when the user initiates the printing pro ...

The JSON code encountered an unexpected token

My current setup involves using webpack with React to load external data from a static json file. Inside my entry.jsx file, I have the following code: const data = require('../data/data.json'); However, this code results in an error message: ...

Tips for positioning content next to a sidebar using basic CSS

I'm having an issue where my content is being hidden behind the sidebar and I want the sidebar to stay fixed on the left side. When I changed position:fixed to float:left in the CSS, it gave me the desired result but the sidebar isn't fixed when ...