G
G
ghrtghrtq2020-04-13 16:52:25
React
ghrtghrtq, 2020-04-13 16:52:25

How to display message not in alert but in modal window?

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 {


But I need to display this message "User with this username already exists" in a modal window . How to implement it?

Do not be afraid that there is a lot of code, I write a lot to make it clearer, I commented out the check I wrote about above.

part of SignupForm.js: (where there is a check that I wrote above):
SignupForm component

const SignupForm = () => {
 const history = useHistory();

    const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({  
      initialValues: {
          username: '',  
    /..........
      },
        validateOnBlur: false,
        validateOnchange: false,
        validationSchema: yup.object().shape({ 
          username: yup.string()      
           .required('This field is required'),
    /.............
      }),  

     onSubmit: async (formValues) => {
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              if(Array.isArray(res)){                // проверка
                  const err = res[0].message;      
                  alert(err);                      
              } else {
                  const token = res.token.token;   
                  localStorage.setItem('myToken', token);
                  console.log('Result!',token);     
                  history.push("/home");
             }
          } catch(e) { 
              console.error(e);
          } finally {
              setSubmitting(false);
          }   
      },  
    });
   return (

    <div className="form">

   <form onSubmit={handleSubmit}>   
       <SignupInput
         label="username"
         id="username" 
         inputProps={{
           name:'username',
           value: values.username,
           onChange: handleChange,
           onBlur: handleBlur,
           disabled: isSubmitting,
       }}
       error={errors.username}
       />
       /............
       <div className="form-button">
       <button type="submit" disabled={isSubmitting}>Submit Form</button>
       </div>
   </form>
       </div>
   );
};



and SignInput.js :
SignInput component

const SignupInput = ({
    label, inputProps, error, id,     
}) => (
        <div className="ffinput">
          <label htmlFor={id} className="ffinput-label">  
            {label}
          </label>
        <input {...inputProps} id={id} />    
          {error && <span className="ffinput-error">{error}</span>} 
        </div>
    );

</spoiler>
SignupInput.propTypes = {                   
    label: PropTypes.string.isRequired,  
    inputProps: PropTypes.instanceOf(Object).isRequired,  
    error: PropTypes.string,
    id: PropTypes.string.isRequired, 
};

SignupInput.defaultProps = { 
    error: '',
}


If something is not clear in the code or you need more information, write in the comments and I will explain.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-04-13
@HistoryART

if(Array.isArray(res)){              
                  const err = res[0].message;      
                  return (<div>{err}</div>);   // Таким-же образом передаётся в компонент                   
              } else {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question