Home > OS >  i have to click on the button twice to post data to api in react
i have to click on the button twice to post data to api in react

Time:07-08

I have console.log(ed) the values while executing and what happens is on the first click, inputValue is sent with a null string to api, then on the next click the inputValue with string is sent to api. I have already changed the value of inputValue using the setter function in input tag with onChange function and then i have called the api so How do i fix it so it sends it on the first click.

const InputEmail = () => {

  const navigate = useNavigate()

  const [inputValue, setInputValue] = useState('')
  const [apiData, setApiData] = useState('')
  const [isError, setIsError] = useState(false)

  // useEffect(() => {
  //   //API()
  // }, [])

  const API = () => {
    console.log(inputValue)
    axios
      .post(url, {
        email: inputValue
      })
      .then((response) => {
        setApiData(response.data)
      })   
      console.log(apiData.is_active)
  }
  
  const handleSubmit = () => {
    API()
    if(apiData.is_active) {
      localStorage.setItem('email',inputValue)
      navigate("/assessment")
    } else {
      setIsError(true)
    }
  }

  return (
    <div className='main'>
        <FormControl>
          <h2 className='text'>Registered Email address</h2>
          <Input id='email' type='email' value={inputValue} onChange={e => setInputValue(e.target.value)}/>
          {
            isError ? <FormHelperText color='red'>Email not found. Please enter registered email</FormHelperText> : null
          }
          <Button
            mt={4}
            colorScheme='teal'
            type='submit'
            onClick={handleSubmit}
          >
            Submit
          </Button>
        </FormControl>
    </div>
  )
}

CodePudding user response:

You must wait for your axios to fetch data from the url before making a handle. It will work if you await untill your async API() functions brings data.

  const API = () => {
    return axios.post(url, {
      email: inputValue,
    });
  };

  const handleSubmit = async () => {
    const response = await API();
    if (response.data.is_active) {
      localStorage.setItem("email", inputValue);
      navigate("/assessment");
    } else {
      setIsError(true);
    }
  };
  • Related