0

I am using react-toolkit Snackbar component with Redux. Each snackbar is modelled as an object in the Redux store. But I want to remove this object everytime the notification times out or is dismissed/hidden. How do I acheive this?

Do I need to manually set onTimeout to dispatch an event everytime I add a notification?

If so, is there a way to add this dispatch in a central place instead of adding it everywhere I dispatch this action?

Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

1 Answers1

0

May be you can use higher order component here.

SnackbarWrapper.js

import React from 'react';
import PropTypes from 'prop-types';

const SnackbarWrapper = (Component) => {
  class Decorated extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = {
        active: props.active
      };
      this.handleSnackbarClick = this.handleSnackbarClick.bind(this);
      this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this);
    }
    componentWillReceiveProps(nextProps) {
      // snackbar activated from outside
      if (this.props.active !== nextProps.active) {
        this.setState({ active: true });
      }
    }
    handleSnackbarClick(event, instance) {
      // snackbar dismissed from inside
      this.setState({ active: false });
      // handle the dispatch in callback function
      this.props.cb();
    }
    handleSnackbarTimeout(event, instance) {
      // snackbar dismissed from inside
      this.setState({ active: false });
      // handle the dispatch in callback function
      this.props.cb();
    }
    render() {
      const { action, label, type, timeout } = this.props;
      return (
        <Component
          action={action}
          label={label}
          type={type}
          timeout={timeout}
          active={this.state.active}
          onClick={this.handleSnackbarClick}
          onTimeout={this.handleSnackbarTimeout}
        />
      );
    }
  }

  Decorated.propTypes = {
    action: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    type: PropTypes.string.isRequired,
    timeout: PropTypes.number.isRequired,
    cb: PropTypes.func.isRequired,
    active: PropTypes.bool.isRequired
  };

  return Decorated;
};

export default SnackbarWrapper;

in your component

import SnackbarWrapper from './SnackBarWrapper';
const RTSnackbar = SnackbarWrapper(Snackbar);
...
<RTSnackbar
  action="Dismiss"
  label="Snackbar action cancel"
  type="cancel"
  timeout={2000}
  cb={this.actionCb}
  active={this.state.active}
 />
Venugopal
  • 1,888
  • 1
  • 17
  • 30