Home > database >  Cannot Update Variable with Onclick Event in React JS
Cannot Update Variable with Onclick Event in React JS

Time:07-20

I am a beginner at React js, and I ahve made this React application which should change the current date by a specific number of months and days at the press of a button. However, this is not working. When I debug the application and press the button multiple times, the date value changes according to console.log(), but not in the viewer. If anyone would be able to give suggestions on what to change for the code, or why this is happening this would be greatly appreciated. Thank you.

import {useEffect, useReducer, useState} from 'react';
import React from 'react';
import ReactDOM from 'react-dom/client';


const DateTest = () => {
    const [date,updateDate] =React.useState(new Date())
    
    const ChangeDate= () => {
        date.setDate(date.getDate()   77)
        date.setMonth(date.getMonth()   8)
        updateDate(date)
        console.log("value of date is: ",date)
    };
    return(
        <>       
            <h1>{date.toString()}</h1>
            <button onClick={ChangeDate}>change</button>
        </>
    )
}

export default DateTest;

//script above is DataTester.js

//script below is the App.js script. 

import './App.css';
import JSONDATA from './MOCK_DATA.json';
import {useState} from 'react';
import DateTest from './DateTester.js';

function App() {


  return(
    <div className="App">
       <DateTest />
    </div>
    
  );
 

}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>

Using F12 to view the console.log results for "date" in the application as it is viewed in the browser

CodePudding user response:

Its because you are updating the date to the same instance, according to react since the reference(memory address) hasn't changed, that means the state hasn't changed so it doesn't trigger a re-render.

Change your code to something like this, just remember you have to pass a new instance to updateDate() in order to see the changes on the screen

const ChangeDate= () => {
        date.setDate(date.getDate()   77)
        date.setMonth(date.getMonth()   8)
        updateDate(new Date(date))
        console.log("value of date is: ",date)
    };

CodePudding user response:

enter image description here

From this image, I managed to fix issues I had with the Date object.

  • Related