score:3
change your tick function to this:
tick = () => {
var timestamp = this.state.datetimestamp + 1;
this.setstate({
datetimestamp: timestamp,
dateformatted: moment(timestamp).tostring()
});
}
this is because from docs :
setstate() does not immediately mutate this.state but creates a pending state transition. accessing this.state after calling this method can potentially return the existing value.
therefore in your next setstate call it use old value. my proposition change this two values at once.
score:8
@krzysztofsztompka is correct, but i would add that maintaining two separate state variables to represent the current date as a number and as a formatted string is an antipattern. derived state variables (i.e., state variables that can be calculated using another state variable) increases the responsibility on the developer to always keep the two state variables in sync. that may not seem too difficult in this simple example, but it can become more difficult in larger, more complicated components/apps. instead, it is generally considered better practice to maintain one source of truth and calculate any derived values on the fly as you need them. here's how i would apply this pattern to your example.
import react from 'react';
import moment from 'moment';
export default class clock extends react.component {
constructor(props) {
super(props);
this.state = {
datetimestamp : date.now()
};
this.tick = this.tick.bind(this);
}
tick() {
this.setstate({
datetimestamp: this.state.datetimestamp + 1
});
}
componentdidmount() {
this.interval = setinterval(this.tick, 1000);
}
componentwillunmount() {
clearinterval(this.interval);
}
render() {
// calculate the formatted date on the fly
const date = moment(this.state.datetimestamp).tostring();
return(
<div classname="clock"> heure locale : {date}</div>
);
}
}
Source: stackoverflow.com
Related Query
- Where to apply my moment() function in a react component?
- React where in the component to add a simple math function
- React stateless component where map function is not returning
- React function style component direct invocation vs jsx - where is the children?
- Apply a function to every single React Component
- What is causing the function to run twice in a react component where there seems to be no prop/state/context change?
- React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
- React - How to force a function component to render?
- React Hooks Error: Hooks can only be called inside the body of a function component
- Creating custom function in React component
- React Warning: Cannot update a component from inside the function body of a different component
- How to apply CSS and Styling to a React component
- React Functional component: calling as function vs. as component
- React : Pass function to child component
- Test a React Component function with Jest
- Function inside functional component in React hooks - Performance
- React w/hooks: prevent re-rendering component with a function as prop
- Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui
- Apply style "cursor: pointer" to all React components with onClick function
- React Pass function to child component
- How to specify function parameters for React component callback with TypeScript?
- React - stateless component, function inside or outside component
- Return DOM element in render function of React component
- Passing a function with React Context API to child component nested deep in the tree
- Converting React function component to class component issue
- React hooks: call component as function vs render as element
- Jest -- Mock a function called inside a React Component
- Test React component method is calling function pass as a prop
- React passing parameter with arrow function in child component
- react router unmount function component
More Query from same tag
- what is the correct type for a React instance of a component in typescript
- How can i convert DatePicker object to datestring
- ReferenceError: Cannot access 'opacity' before initialization in react
- getting error Dropdown `value` must be an array when `multiple` is set
- How to display an image in react from PostgreSQL
- PropTypes for react-redux/react-router connect & withRouter functions' ownProps parameter?
- useRef current getting its value only on second update
- goBack() button doesn't work. HashRouter React
- I don't know how to save the localStorage when I refresh the page
- How to deal with a query parameter in react router
- Meteor-React delete post with submit modal (post not defined)
- Show Date/time in x axis using react d3
- Setting the type to the incoming apiye state
- Style not applying on select tag in react application
- React useEffect return best practice
- Use history.push in action creator with react-router-v4?
- setState doesnot change the state in React
- Can we print a path-defined pdf using reactjs?
- Option filter in select box in React
- Can I add optional attributes to an element in React?
- How to use LESS variable in React JS
- How to get rid of "Sort" & "Delete" columns in MDBootstrap React MDBTableEditable component?
- React - Hooks + Context - Is this a good way to do global state management?
- Context API weird situation
- How to customize a column in react table 7
- React: how to prevent api calls in ComponentDidMount and in ComponentDidUpdate override each other
- How to add a multilingual support in react js with api call?
- How to control the open state of two modals in sequence
- Unhandled Rejection (TypeError): Cannot read property of undefined
- How to consume API in Redux application