Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something once, then every 15 seconds in react js

I have the following code:

var Panel = React.createClass({

  getInitialState: function () {
    return {
      user_id: null,
      blogs: null,
      error: false,
      error_code: '',
      error_code: ''
    };
  },

  shouldComponentUpdate: function(nextProps, nextState) {
    if (nextState.error !== this.state.error ||
        nextState.blogs !== this.state.blogs ||
        nextState.error_code !== this.state.error_code
      ) {
      return true;
    }
  },

  componentDidMount: function() {
    var self = this;
    var pollingInterval = setInterval(function() {
      $.get(self.props.source, function(result) {
        if (self.isMounted()) {
          self.setState({
            error: false,
            error_code: '',
            error_message: '',
            blogs: result.user.blogs,
            user_id: result.user.id
          });
        }
      }.bind(self)).fail(function(response) {
        self.setState({
          error: true,
          error_code: response.status,
          error_message: response.statusText
        });
      }.bind(self));
    }, 1000);
  },

  render: function() { ... }

});

The important part to focus on is the componentDidMount This will fetch every second, regardless if there is an error or not. The render function, assuming theres an error, will display the appropriate method. So for all intense and purpose, this code does exactly what I want it to do, it fetches, if it fails, it fetches again until it succeeds.

But I need to make some changes, and this is where I am lost. I want to say: Fetch once, pass or fail - it doesn't matter. THEN every 15 seconds after that initial fetch, try again - regardless of pass or fail

I would normally spin up a backbone collection and router along with a poll helper to do all this, but in this specific case there is no need for the extra overhead. So thats where I am stumped. How do I accomplish what I am trying to achieve?

like image 540
TheWebs Avatar asked Feb 27 '15 17:02

TheWebs


People also ask

How do you do something every second in React?

Let's explore how to use setInterval in React. The TL;DR: useEffect(() => { const interval = setInterval(() => { console. log('This will run every second!'

How do you set interval timer in React?

js import React from 'react'; import { useState } from 'react'; const Timer = () => { const [days, setDays] = useState(0); const [hours, setHours] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); const deadline = "December, 31, 2022"; const getTime = () => { const ...

How do you call a function after 2 seconds React?

The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);

How do you call API after 5 seconds in React JS?

Using setInterval() We can pass an API call inside the setInterval() to make it run repeatedly. const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); }, 2000); Once this interval is created, it will send the API request after every two seconds.


1 Answers

You should be able to just refactor your code a bit to be able to call your polling function a few different ways (like manually for example and then at a specified interval):

componentDidMount: function() {
  this.startPolling();
},

componentWillUnmount: function() {
    if (this._timer) {
      clearInterval(this._timer);
      this._timer = null;
    }
},

startPolling: function() {
    var self = this;
    setTimeout(function() {
      if (!self.isMounted()) { return; } // abandon 
      self.poll(); // do it once and then start it up ...
      self._timer = setInterval(self.poll.bind(self), 15000);
    }, 1000);
},

poll: function() {
    var self = this;
    $.get(self.props.source, function(result) {
      if (self.isMounted()) {
        self.setState({
          error: false,
          error_code: '',
          error_message: '',
          blogs: result.user.blogs,
          user_id: result.user.id
        });
      }
    }).fail(function(response) {
      self.setState({
        error: true,
        error_code: response.status,
        error_message: response.statusText
      });
    });
}
like image 57
WiredPrairie Avatar answered Oct 03 '22 14:10

WiredPrairie