Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating state every x seconds

Tags:

react-native

I am trying to update a state every 3 seconds.

export default class Calendar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      timeLineTop: 75,
    };
  }

render() {
    this.state.timeLineTop = setInterval(function () {
      let d = new Date();
      let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;

      return result;
    }, 3000);

    <View style={[
          { top: this.state.timeLineTop },
        ]}></View>
  }
}

Why will this not update my views position every 3 seconds?

like image 458
jt123 Avatar asked Dec 12 '15 18:12

jt123


People also ask

How do I change my state every second?

To update React component every second with JavaScript, we can use the setInterval function to update a state in the useEffect hook. const [time, setTime] = useState(Date. now()); useEffect(() => { const interval = setInterval(() => setTime(Date.

Why is state not updating directly?

The reason why the state doesn't update immediately is because for each render, the state is immutable. …are both constants values ! So they're immutable. The state remains constant inside the render but can be changed between two renders.

How do I preserve state on refresh?

To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.


6 Answers

This code work in React Native 0.47.1

import TimerMixin from 'react-timer-mixin';

mixins: [TimerMixin];

export class MyClass extends Component {

    componentDidMount() {

        this.interval = setInterval(() => {
            console.log("Hi");

        }, 6000); //6 seconds

    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }
}
like image 101
Tiago Mendes Avatar answered Oct 08 '22 18:10

Tiago Mendes


ES6 solution which worked for me, I found it here https://github.com/reactjs/react-timer-mixin/issues/4

componentDidMount() {
 this.timer = setTimeout(() => {
  console.log('I do not leak!');
 }, 5000);
}

componentWillUnmount() {
 clearTimeout(this.timer);
}
like image 40
Sashko Avatar answered Oct 08 '22 20:10

Sashko


** Updated to implement TimerMixin

You need to call a this.setState to update a state variable, and as specified by @eyal83, use the TimerMixin for setTimeout & setInterval:

var TimerMixin = require('react-timer-mixin');

componentDidMount: function() {
  this.setInterval( () => { 
       let d = new Date();
       let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;
       this.setState({
           timeLineTop: result
       })
    }, 500);
}

I've also set up a basic app resetting the state variable with a setInterval here, code is below. https://rnplay.org/apps/9gD-Nw

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var TimerMixin = require('react-timer-mixin');

var SampleApp = React.createClass({
  mixins: [TimerMixin],
  getInitialState: function() {
        return {
            timeLineTop: 75
        }
    },

  componentDidMount: function() {
    this.setInterval( () => { 
      this.setState({
        timeLineTop: this.state.timeLineTop+1
      })
    }, 500);
  },

  render: function() {

    return (
      <View style={styles.container}>
       <View style={[
          { marginTop: this.state.timeLineTop },
        ]}><Text>TOP - {this.state.timeLineTop}</Text></View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:60,
  },
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);
like image 38
Nader Dabit Avatar answered Oct 08 '22 20:10

Nader Dabit


Using setTimeout and setInterval globally is a very bad idea.

We strongly discourage using the global setTimeout(...) and recommend instead that you use this.setTimeout(...) provided by react-timer-mixin. This will eliminate a lot of hard work tracking down bugs, such as crashes caused by timeouts firing after a component has been unmounted.

More info here: https://facebook.github.io/react-native/docs/timers.html#timermixin

Include the timer mixin like this:

var TimerMixin = require('react-timer-mixin');

var Component = React.createClass({
  mixins: [TimerMixin],
  componentDidMount: function() {
    this.setInterval(
      () => { console.log('I do not leak!'); },
      500
    );
  }
});
like image 23
eyal83 Avatar answered Oct 08 '22 20:10

eyal83


In ES6, you should use react-mixin, (https://github.com/brigand/react-mixin), example:

var reactMixin = require('react-mixin');
var someMixin = require('some-mixin');
class Foo extends React.Component {
    render: function(){ return <div /> }    
}
reactMixin(Foo.prototype, someMixin);
reactMixin(Foo.prototype, someOtherMixin);
like image 22
dayudodo Avatar answered Oct 08 '22 19:10

dayudodo


This is my code using component..

    import TimerMixin from 'react-timer-mixin';


    export default class MyComponent extends Component {

        componentDidMount(){
            TimerMixin.setTimeout.call(this, () =>{ 
                this.getData()
            },2000);
        }

        getData(){
            //call API HERE

        }

    }
like image 35
keithics Avatar answered Oct 08 '22 18:10

keithics