Home > Mobile >  Display Alerts and Remove it using States
Display Alerts and Remove it using States

Time:10-06

When I display some alerts, and close one of the alert, I need the previous alerts to stay when I refresh the page. So, somehow I need to save the state of these alerts in local storage. Any solution for this?

P.S I need this implementation using React States.

CodePudding user response:

I remember answering a similar question recently, but now I am unable to find that answer (most probably it might have been deleted). Here's a way to do it.

I guess you can save the state to the localStorage this way:

  • window.localStorage.setItem()
  • window.localStorage.getItem()

Now what I have done so far is when I do any change to the states, I do:

if (window.localStorage) {
  window.localStorage.setItem('alerts', JSON.stringify(alerts));
}

And then when I start my app, i.e., on componentDidMount, I do:

if (window.localStorage && window.localStorage.getItem('alerts')) {
  this.setState(JSON.parse(window.localStorage.getItem('alerts')));
}

So here's the full code:

componentDidMount() {
  if (window.localStorage && window.localStorage.getItem('alerts')) {
    this.setState(JSON.parse(window.localStorage.getItem('alerts')));
  }
  // subscribe to new alert notifications
  this.subscription = alertService.onAlert(this.props.id).subscribe(alert => {
    // clear alerts when an empty alert is received
    if (!alert.message) {
      // filter out alerts without 'keepAfterRouteChange' flag
      const alerts = this.state.alerts.filter(x => x.keepAfterRouteChange);
      // remove 'keepAfterRouteChange' flag on the rest
      alerts.forEach(x => delete x.keepAfterRouteChange);
      this.setState({ alerts });
      if (window.localStorage) {
        window.localStorage.setItem('alerts', JSON.stringify(alerts));
      }
      return;
    }
    // add alert to array
    this.setState({ alerts: [...this.state.alerts, alert] });
    // auto close alert if required
    if (alert.autoClose) {
      setTimeout(() => this.removeAlert(alert), 3000);
    }
  });
  // clear alerts on location change
  this.historyUnlisten = history.listen(() => {
    alertService.clear(this.props.id);
  });
}

Demo Forked StackBlitz: https://stackblitz.com/edit/react-alerts-rv1qc8

  • Related