我必须单击两次按钮才能将数据发布到React中的API
我有console.log(ed)执行时的值,并且首次单击时发生的情况是,输入值是将null字符串发送到API的,然后在下一次单击“ InputValue”中,带有字符串的InputValue将发送到API。我已经使用onChange函数在输入标签中使用setter函数更改了InputValue的值,然后我调用了API,因此我如何修复它,以便在第一次单击时将其发送。
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>
)
}
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>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须等待Axios在制作手柄之前从URL获取数据。如果您等待取消异步API()功能会带来数据,则它将起作用。
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.