Bargain23
Bargain23

Reputation: 1973

React component won't stop fetching data because of setInterval

I'm using setInterval to poll requests and make my app real-time, and I think it might be the culprit why the fetch requests keep coming. This is my React component:

export default class ChatBox extends Component<ChatBoxProps, ChatBoxState> {
  interval = setInterval(() => this.fetchComments(), 500)
  state = {
    comments: [],
    content: '',
  }

  componentDidMount () {
    this.interval = setInterval(() => this.fetchComments(), 500)
    this.scrollToBottom()
  }

  componentDidUpdate () {
    this.scrollToBottom()
  }

  componentWillUnmount () {
    clearInterval(this.interval)
  }

  fetchComments = () => {
    fetchComments().then(comments => {
      this.setState({ comments })
    })
  }
}

Is there a way to prevent this behavior?

Upvotes: 0

Views: 656

Answers (2)

trixn
trixn

Reputation: 16309

You start two intervals and forget about the first one.

The first will be started on instance initialisation and the second in componentDidMount(). But the second will override the reference to the first interval which will then not be removed in componentWillUnmount(). You should set your interval only in componentDidMount() and init it with null:

export default class ChatBox extends Component<ChatBoxProps, ChatBoxState> {
    interval = null;

    componentDidMount () {
        this.interval = setInterval(() => this.fetchComments(), 500);
        /* ... */
    }

    componentWillUnmount () {
        clearInterval(this.interval);
    }

    /* ... */
}

Upvotes: 1

Javed Shaikh
Javed Shaikh

Reputation: 681

You missed this.interval. you have set two intervals. please removed atleast one. you have cleared this.interval not interval.

export default class ChatBox extends Component<ChatBoxProps, ChatBoxState> {

  state = {
    comments: [],
    content: '',
  }

  componentDidMount () {
    this.interval = setInterval(() => this.fetchComments(), 500)
    this.scrollToBottom()
  }

  componentDidUpdate () {
    this.scrollToBottom()
  }

  componentWillUnmount () {
    clearInterval(this.interval)
  }

  fetchComments = () => {
    fetchComments().then(comments => {
      this.setState({ comments })
    })
  }
}

Upvotes: 3

Related Questions