G
G
ghrtghrtq2020-04-13 18:44:07
React
ghrtghrtq, 2020-04-13 18:44:07

What is wrong here in the code that the modal window does not appear (another question)?

I am doing registration in my app. When I submit a form to my local server and this server already has a user with this username, it returns a 400 error and response:

response when error

[{
        "message": "User with this username already exists",
        "field": "username",
        "validation": "unique"
}]



Now I am displaying this message in alert:
if(Array.isArray(res)){              
                  const err = res[0].message;      
                  alert(err);                      
              } else {

And the error is displayed by an alert on my screen. Everything is fine.

But I need to display message: "User with this username already exists" in modal window. And I wrote this:
if(Array.isArray(res)){              
     const err = res[0].message;      
     return (<div className="err-response">{err}</div>);

and in style.css I wrote:
.err-response{
    width: 1000px;
    height: 500px;
    background: grey;
}


But the modal window does not appear. What is wrong here in the code that the modal window does not appear?

SignupForm.js - Code where part of the code I wrote about above (I commented out the lines):
const SignupForm = () => {

 const {handleSubmit, values, handleChange, errors, handleBlur} = useFormik({ 
 /......
     onSubmit: async (formValues) => {
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              if(Array.isArray(res)){              //this
                  const err = res[0].message;      //this
                  alert(err);                      //this
              } else {
                  /...... 
             }
          } catch(e) { 
              console.error(e);
          }  
      },  
    });
   return (
    <div className="form">

   <form onSubmit={handleSubmit}>   
       /............

       <button type="submit" disabled={isSubmitting}>Submit Form</button>
   </form>
       </div>
   );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-04-13
@ghrtghrtq

The fact is that

onSubmit: async (formValues) => {
          try {
              const res = await .........
              if(Array.isArray(res)){         
                  const err = res[0].message;     
                  return (<div className="err-response">{err}</div>);
// ^ это не return из реакт-компонента, а из функции обработчика сабмита формы
// рендериться ничего не будет
              }
      },

the output is such that in case of an error you would write it to the state of the component, something like
const SignupForm = () => { 

  const [errorMessage, setErrorMessage] = React.useState(null)

.... 
if(Array.isArray(res)){        
  // то есть ошибка это когда res - массив? 
  setErrorMessage (res[0].message)
  // теперь в errorMessage у нас текст ошибки, а не null
}

....

return (
  <div className="form">
    { errorMessage && <p>${errorMessage}</p> }
    {/* ^ если там null, то ничего не будет писаться  */}
  
  .....
  </div>
)

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question