简体   繁体   中英

check if user available before submitting form in reactjs

i'm using formik and in my Register form i have on textfield username, i want to check if the username available or not before submitting the form so i make one function onhandle change event as:

 <FormControl >
            <TextField 
              name="userName"
              onBlur={handleBlur}
              value={values.userName}
              onChange={(e)=>{handleChange(e);checkAvailabilty(e)}}
              error={touched.userName && Boolean(errors.userName) }
              helperText={touched.userName && errors.userName }
           />
            <FormHelperText error>
            {userError ? userError  : null}
            </FormHelperText>

</FormControl>

and the function is:

const checkAvailabilty = async(e) =>{
  try{
  let response = await axios.get(`${state.baseUrl}users/is_available/${e.target.value}`)
    if(response.status.code === 200)
    {setUserError(false)}
  }
  catch(error){
    if(error.response.status=== 409)
    {setUserError("available")}
  }
}

so whenever any user exist it will set user error with available

but the problem is setuserError is not set accordingly on http code 200 it will not set with false once it set with available it keep set available.

I don't have enough reputation yet to comment unfortunately, but there were a few things I wanted to ask:

  • Does your state.baseUrl end with a / ?
  • Wouldn't it be better to respond with a 404 Not found instead of 409 ?

I also believe you only need to check response.status and not response.status.code to check the response code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM