Answer a question

So I'm trying to do error handling using a library called react-alert.

I'm using Axios as my REST handler. I created an action and a reducer, which are both working fine; saw my state update in my DevTools extension when I make a post request.

Here's my functional component called Alert.js

import React, { Fragment, useState } from "react";
import { useAlert } from "react-alert";
import { useSelector } from "react-redux";
import { useEffect } from "react";

export default function Alert(props) {
  const alert = useAlert();
  const error = useSelector((state) => state.errors.errors);

  const [errorMSG, setERRORS] = useState();

  useEffect(() => {
    if (error !== errorMSG) {
      setERRORS(error);
      alert.show(errorMSG);
    } else {
      alert.show("Welcome!");
    }
  }, [errorMSG]);

  return <Fragment />;

then I called it in my main App.js

//Main Imports
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";

// React Alert

import { Provider as AlertProvider } from "react-alert";
import AlertTemplate from "react-alert-template-basic";
import Alert from "./layout/Alert";

const alertOptions = {
  timeout: 3000,
  position: "top center",
};

//Components import
import Header from "./layout/Header";
import Dashboard from "./products/Dashboard";

//Redux import
import { Provider } from "react-redux";
import store from "../store";

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <AlertProvider template={AlertTemplate} {...alertOptions}>
          <Alert />
          <Fragment>
            <Header />
            <div className="container-fluid">
              <Dashboard />
            </div>
          </Fragment>
        </AlertProvider>
      </Provider>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

I do see the Welcome! when the app mounts, but when I have an error I see nothing. Could anyone help me find a solution to this; would be really appreciated.

Answers

You see "Welcome" because when your component mounts first time, it calls the useEffect hook. But the useEffect hook isn't getting triggered afterwards because of the wrong dependency item provided for the useEffect. You need to add error instead of errorMSG, because error is coming from your store and you want to show the message when there is a new error emitted:

 useEffect(() => {
    if (error !== errorMSG) {
      setERRORS(error);
      alert.show(errorMSG);
    } else {
      alert.show("Welcome!");
    }
  }, [error]);
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐