title: how to remove error messages asynchronously in React
body: <p>I'm fetching an array of errors, one of them says <code>"Username is taken"</code> and the other one says <code>"Password must be at least 5 chars"</code>.</p>
  
  <p>It's displayed like this in React.</p>
  
  <pre><code>{this.props.auth.errors ? (
      this.props.auth.errors.map( (err, i) =&gt; (
          &lt;div key={i} style={{color: 'red'}}&gt;
              {err}      
          &lt;/div&gt;
      ))                  
  
  ):(
      null
  )}
  </code></pre>
  
  <p><code>this.props.auth.errors</code> is an array containing the error messages, after registerUser gets called. </p>
  
  <p><strong>Actions.js</strong></p>
  
  <pre><code>export const registerUser = (userData) =&gt; dispatch =&gt; {
  
      Axios
        .post('/users/register', userData)
        .then( res =&gt; {
          const token = res.data.token;
          // console.log(token);
          // pass the token in session
          sessionStorage.setItem("jwtToken", token);
          // set the auth token
          setAuthToken(token);
          // decode the auth token
          const decoded = jwt_decode(token);
          // pass the decoded token
          dispatch(setCurrentUser(decoded))     
          // this.props.history.push("/dashboard")
        }).catch( err =&gt; {
  
          //  console.log(err.response.data.error[0].msg)
  
           Object.keys(err.response.data.error).forEach( (key) =&gt; {
              dispatch({
                  type: GET_ERRORS,
                  payload: err.response.data.error[key].msg
              })   
           })
  
      })    
  };
  </code></pre>
  
  <p>How would i be able to remove the error, if for example the user does make a password that is minimum of 5 chars, or uses a username that does exist ? You know what i mean ? Also could this be done asynchronously ? As if you were to sign in or register on a top end social media website where it shows the error on async and gos away once you complied to the error message.</p>
  
  <p>Full react code </p>
  
  <p><strong>SignUp.js</strong> </p>
  
  <pre><code>import React, { Component } from "react";
  import {connect} from 'react-redux';
  import {registerUser} from '../actions/authActions';
  import TextField from '@material-ui/core/TextField';
  import Button from '@material-ui/core/Button';
  import Grid from '@material-ui/core/Grid';
  import PropTypes from "prop-types";
  import Typography from '@material-ui/core/Typography';
  class SignUp extends Component{
      constructor() {
          super();
  
          this.state = {
              formData:{
                  email:'',
                  username:'',
                  password:'',
                  passwordConf: "",
                  isAuthenticated: false,
              },
              errors:{},
              passErr:null
          }
  
      }
  
      componentDidMount() {
          // console.log(this.props.auth);
          if (this.props.auth.isAuthenticated) {
            this.props.history.push("/dashboard");
          }
  
        }
      //   this line is magic, redirects to the dashboard after user signs up
      componentWillReceiveProps(nextProps) {
          if (nextProps.auth.isAuthenticated) {
            this.props.history.push("/dashboard");
          }
          if (nextProps.errors) {
            this.setState({ errors: nextProps.errors });
          }
      }
  
      handleChange = (e) =&gt; {
          e.preventDefault();
          const {formData} = this.state;
          this.setState({
              formData: {
                  ...formData,
                  [e.target.name]: e.target.value
              }
          });
      }
      handleSubmit = (e) =&gt; {
          e.preventDefault();
          const {formData} = this.state;
          const {username, email, password, passwordConf} = formData;
          this.setState({
              username: this.state.username,
              password: this.state.password,
              passwordConf: this.state.passwordConf,
              email: this.state.email
          });
          const creds = {
              username,
              email,
              password
          }
  
          console.log(creds);
          if (password === passwordConf) {
              this.props.registerUser(creds, this.props.history);
          } else {
              this.setState({passErr: "Passwords Don't Match"})
          }
      }
  
  
  
      render(){
          return(
              &lt;div&gt;
                  &lt;Grid container justify="center" spacing={0}&gt;
                      &lt;Grid item sm={10} md={6} lg={4} style={{ margin:'20px 0px'}}&gt;
                      &lt;Typography variant="h4" style={{ letterSpacing: '2px'}} &gt;
                           Sign Up
                      &lt;/Typography&gt;
  
                  {this.props.auth.errors ? (
                      this.props.auth.errors.map( (err, i) =&gt; (
                          &lt;div key={i} style={{color: 'red'}}&gt;
                              {err}
  
                          &lt;/div&gt;
                      ))                  
  
                  ):(
                      null
                  )}
                  {this.state.passErr &amp;&amp; (
                      &lt;div style={{color: 'red'}}&gt;
                          {this.state.passErr}
                      &lt;/div&gt;
                  )}
  
  
                  &lt;form onSubmit={this.handleSubmit}&gt;
                      &lt;TextField
                          label="Username"
                          style={{width: '100%' }}
                          name="username"
                          value={this.state.username}
                          onChange={this.handleChange}
                          margin="normal"
                          /&gt;
                      &lt;br&gt;&lt;/br&gt;
                      &lt;TextField
                          label="Email"
                          className=""
                          style={{width: '100%' }}
                          name="email"
                          value={this.state.email}
                          onChange={this.handleChange}
                          margin="normal"
                         /&gt;
                      &lt;br&gt;&lt;/br&gt;
                      &lt;TextField
                          label="Password"
                          name="password"
                          type="password"
                          style={{width: '100%' }}
                          className=""
                          value={this.state.password}
                          onChange={this.handleChange}
                          margin="normal"
                          /&gt;
                      &lt;br&gt;&lt;/br&gt;
                      &lt;TextField
                          label="Confirm Password"
                          name="passwordConf"
                          type="password"
                          style={{width: '100%' }}
                          className=""
                          value={this.state.passwordConf}
                          onChange={this.handleChange}
                          margin="normal"
                         /&gt;
                      &lt;br&gt;&lt;/br&gt;
                      &lt;br&gt;&lt;/br&gt;
                      &lt;Button variant="outlined" color="primary" type="submit"&gt;
                          Sign Up
                      &lt;/Button&gt;
  
                  &lt;/form&gt;
                  &lt;/Grid&gt;
              &lt;/Grid&gt;
              &lt;/div&gt;
  
          )
      }
  
  
  }
  
  SignUp.propTypes = {
      registerUser: PropTypes.func.isRequired,
      auth: PropTypes.object.isRequired,
  };
  
  const mapStateToProps = (state) =&gt; ({
      auth: state.auth
  })
  
  const mapDispatchToProps = (dispatch) =&gt; ({
      registerUser: (userData) =&gt; dispatch(registerUser(userData))
  })
  
  export default connect(mapStateToProps, mapDispatchToProps)(SignUp)
  </code></pre>
  
  <p><strong>AuthReducer</strong></p>
  
  <pre><code>import {SET_CURRENT_USER, GET_ERRORS} from '../actions/types';
  import isEmpty from '../actions/utils/isEmpty';
  
  const initialState = {
      isAuthenticated: false,
      errors: []
  }
  
  
  export default  (state = initialState, action) =&gt; {
      switch (action.type) {
          case SET_CURRENT_USER:
              return{
                  ...state,
                  isAuthenticated: !isEmpty(action.payload),
                  user:action.payload
              }
  
          case GET_ERRORS:
              console.log(action.payload)
              // allows for us to loop through an array of errors.
              return Object.assign({}, state, {
                  errors: [...state.errors, action.payload]
              })     
  
          default:
              return state;
      }
  }
  </code></pre>
  
  <p>a UI example of how this plays out</p>
  
  <p><a href="https://i.stack.imgur.com/pwH6j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pwH6j.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/ZXYKP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZXYKP.png" alt="enter image description here"></a></p>