Search code examples
javascriptreactjsmessage

React Error Message Persists even after Refreshing the page


I am working on a project in React. In the Register Page, I add all errors in a Message component. During development, whenever a React error occurs (like Cannot read properties of undefined), the error message continues to be displayed in the component until I successfully register. I want the error message to disappear whenever I reload the page.

I tried putting the below condition to get rid of the error message but it didn't work. I don't understand why the error message persists.

{error ? <Message variant="danger">{error}</Message> : ""}

Edit: I am using redux, so the error is being returned by an API call.

  const userCreate = useSelector((state) => state.userCreate);
  const { error, success, loading } = userCreate;

After I return this error in the Message component, it isn't disappearing. Once I even had to clear localStorage to get rid of it. The error was Cannot read properties of undefined, reading password.


Solution

  • If you are using functional component then you can use the useEffect() hook and set the error value to false, so that whenever you are reloading the page error value will be false and your error message will not appear and for class based component you can use componentDidMount() to do the same.

    const [showMessage,setShowMessage] = useState(false);
    useEffect(()=>{
       if(error){
          showMessage(true);
       }
    },[error])
    
    {showMessage ? <Message variant="danger">{error}</Message> : ""}