'React Hook Form Validation Problem with Filled Form with Fetched Values
For my react app, I need a 'Update Article' component. I am initially filling the form with fetching the values from the existing article in backend. But when I click Submit button without changing anything It's still returning errors. What could be the problem? This is the code:
const [articleTitle, setArticleTitle] = useState("");
..otherStates
const [getArticleRes, getArticleReq] = useApi();
const {
register,
handleSubmit,
formState: { errors, }
} = useForm();
useEffect(() => {
getArticleReq(urls.articlesUrl + "/" + articleId, { method: "GET" });
}, []);
useEffect(() => {
if (getArticleRes.status) {
if (getArticleRes.status === 200) {
const { title, body, imguri } = getArticleRes.data.result;
setArticleTitle(title);
setArticleBody(body);
setImageData(imguri);
} else if (getArticleRes.status === 400) {
console.log("SIKINTI BÜYÜK");
} else {
}
}
}, [getArticleRes.data, getArticleRes.status]);
//Updating the article here. Totatlly works but needed to delete for the code limitation
return (
<div>
<form onSubmit={handleSubmit(editArticle)}>
<TextField
sx={{ width: "100%" }}
margin="normal"
id="articleTitle"
name="articleTitle"
label="Title"
variant="outlined"
value={articleTitle}
{...register("articleTitle", {
required: true,
minLength: 8,
onChange: (e) => setArticleTitle(e.target.value),
})}
/>
{ errors.articleTitle && errors.articleTitle.type === "required" && (
<span className={classes.errorMessage}>Title is Required</span>
)}
{ errors.articleTitle && errors.articleTitle.type === "minLength" && (
<span className={classes.errorMessage}>
Minimum characters 8 required
</span>
)}
...and other textfields
<Button
type="submit"
variant="contained"
>
Submit Article
</Button>
</form>
</div> ```
[This is the situation when I try to submit with changing anything with the existing fetched data][1]
[1]: https://i.stack.imgur.com/j0U8h.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
