ReactJS: onSubmit depending on API response close modal box

Why the state value is not updating after the form submit ? As i need to close the model after the successfully login.

I have tried to check with this useCallback hook but not able to close the dialogbox.

function HeaderComponent(props) {

  const [loggedIn, setIsLoggedIn] = useState(false);
  const [show, setShow] = useState(false);
  const [modelShow, setmodelShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  const registerUser = async event => {
    event.preventDefault()

    axios.post(`{api_url}/user/login`, data, { 
    })
    .then((response) => {
      localStorage.setItem("token", userDetails.auth_token);
      setmodelShow(true)
      router.push('/')
    })
    .catch((error)) => {
      setmodelShow(false)
    }
  }

  return (
  <Modal show={show} onHide={handleClose} className={show ? 'intro' : ''}>
    <form onSubmit={registerUser}>
      <input type="email" />
      <div className="form-group">
        { 
          modelShow ? <input type="submit" name="" value="Login" onClick={handleClose}/>
          : <input type="submit" name="" value="Login" />
        }
      </div>
    </form>
  </Model>
  )
}

export default React.memo(HeaderComponent);

Answer

There are needs a little modification in your code like

return ( !modelShow ? <Modal show={show} onHide={handleClose} className={show ? 'intro' : ''}>
    <form onSubmit={registerUser}>
      <input type="email" />
      <div className="form-group">
        { 
          modelShow ? <input type="submit" name="" value="Login" onClick={handleClose}/>
          : <input type="submit" name="" value="Login" />
        }
      </div>
    </form>
  </Model> : null )

Leave a Reply

Your email address will not be published. Required fields are marked *