React continuous polling

Posted on

Problem

I have a Notifications component in my React app, which continuously polls the server for new notifications. The app uses Redux for storing notifications. When a new notification is received, it is shown on screen. Here’s what the code looks like:

import * as React from 'react'
import { connect } from 'react-redux'

interface ReduxProps {
    notifications: INotification[]
    fetchNotifications: () => any
}

interface IProps extends ReduxProps {}

class NotificationsWidget extends React.Component<IProps> {
    timer: number

    refreshNotifications = () => {
        this.props.fetchNotifications()
    }

    componentDidMount() {
        this.timer = window.setInterval(() => this.refreshNotifications(), 3000)
    }

    render() {
        // ... Show `this.props.notifications`.
    }
}

const mapStateToProps = (state: any) => ({
    notifications: state.notifications.items
})

export default connect(mapStateToProps, {fetchNotifications})(NotificationsWidget)

Is this the correct way to go about polling with a React/Redux app? Is there a better way to do polling, or is there an alternative way to push notifications to the browser without polling?

Solution

There are many ways you could implement polling but this one is valid enough for a lot of cases. You could hide your timer off in a redux action somewhere if you were so inclined.

It’s worth highlighting that you should clear out your timer when the Component unmounts.

componentWillUnmount() {
    window.clearInterval(this.timer)
}

Leave a Reply

Your email address will not be published. Required fields are marked *