Home > Net >  check if user available before submitting form in reactjs
check if user available before submitting form in reactjs

Time:12-23

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.

CodePudding user response:

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.

  • Related