monkeys73
monkeys73

Reputation: 171

ReactJS timestamp

Here is my code -

const [time, setTime] = useState('')

const getRefresh = () => {
        pageContext.refreshList()
        var today = new Date()
        var currentTime = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
        setTime(currentTime)
    }

<div className="bttn-layout">
    <LastRefreshed getRefresh={time}/>
    <Button label="Refresh" onClick={e =>getRefresh()} />
</div>

Here is the code in my 'LastRefreshed' component -

const LastRefreshed = (props) => {

   
    return (
        <div>
            <p>Last Refreshed: {props.time} </p>
        </div>

    )
}


export default LastRefreshed;

Ideally, when the refresh button is clicked, it will call the getRefresh function which updates a list on my home page as well as passing the current timestamp to 'time' state. This state is then used by my 'LastRefreshed' function and will therefore show the last refreshed timestamp. At the moment, the code above is not working. The getRefresh function is definitely being called however I am struggling with getting the time to show in my LastRefreshed component. I am wondering if it's because the state is not properly updating? Any help appreciated!

Upvotes: 2

Views: 1886

Answers (3)

Sarun UK
Sarun UK

Reputation: 6766

<LastRefreshed time={time}/>

Code:-

const [time, setTime] = useState('');

const getRefresh = () => {
        pageContext.refreshList();
        var today = new Date();
        var currentTime = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
        setTime(currentTime);
    }

<div className="bttn-layout">
    // component property should be `time` instead of `getRefresh`
    <LastRefreshed time={time}/> 
    //Note:- As you are not passing any arguments, directly mention getRefresh function
    <Button label="Refresh" onClick={getRefresh} /> 
</div>

LastRefreshedComponent:-

Note:- Here followed the shorthand syntax of arrow function,

 // Also used object destructuring for the props
 const LastRefreshed = ({time}) =>  
             <div>
                <p>Last Refreshed: {time} </p>
            </div>;
    
    export default LastRefreshed;

Upvotes: 0

Justin
Justin

Reputation: 406

change
<p>Last Refreshed: {props.time} </p> to <p>Last Refreshed: {props.getRefresh} </p>
or
<LastRefreshed getRefresh={time}/> to <LastRefreshed time={time}/>

The name of your prop parameter does not match the name used in the component

Upvotes: 0

NinjaDev
NinjaDev

Reputation: 402

<div className="bttn-layout">
    <LastRefreshed time={time}/>
    <Button label="Refresh" onClick={e =>getRefresh()} />
</div>

You should change the props name of LastRefreshed to time.

Upvotes: 1

Related Questions