Всем привет, почему не криво отрабатывает валидация? (даже если в поле что-то есть все равно думает что компонент пустой)
import
React,
{useState
} from "react";
import
{Formik,
Form, useField
} from "formik";
import "../assets/css/styles-custom.css";
import "../assets/css/formStyles.css";
import
{makeStyles
} from "@material-ui/core/styles";
import
{Button} from "@material-ui/core";
import
{useDispatch
} from "react-redux";
import * as Yup from "yup";
import
{ADD_POSTS_FAILURE,
ADD_POSTS_REQUEST,
ADD_POSTS_SUCCESS} from "../redux/types";
const MyTextInput =
({label, setValue, ...props
}) =>
{
const
[field, meta
] = useField
(props
);
return
(
<>
<label htmlFor=
{props.id || props.name
}>{label
}</label
>
<input className="text-input"
{...field
} {...props
} onChange=
{e => setValue
(e.target.value
)}/>
{meta.touched && meta.error ?
(
<div className="error"
>{meta.error
}</div
>
) : null
}
</>
);
};
const MyTextArea =
({label, setValue, ...props
}) =>
{
const
[field, meta
] = useField(props);
return (
<>
<label htmlFor={
props.id ||
props.name}>{label}</label>
<textarea className="text-area" {...field} {...props} onChange={e => setValue(e.target.value)}/>
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</>
);
};
const PostForm = ({userID}) => {
const useStyles = makeStyles({
background: {
background: '#fff'
},
form: {
display: 'flex',
flexDirection: 'column',
padding: '1rem 3rem'
},
title: {
fontSize: '3rem',
fontFamily: 'monospace',
letterSpacing: '2px',
textAlign: 'center'
}
})
const classes = useStyles()
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const dispatch = useDispatch()
const formSubmit = (e) => {
try {
dispatch({type: ADD_POSTS_REQUEST})
fetch('
https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title,
body,
userId: userID
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => dispatch({type: ADD_POSTS_SUCCESS, payload: json})
);
} catch (error) {
const errorMsg = error.message
dispatch({type: ADD_POSTS_FAILURE, payload: errorMsg})
}
}
return (
<div className={classes.background}>
<h1 className={classes.title}>Add Post</h1>
<Formik
initialValues={{
title,
body
}}
validationSchema={Yup.object({
title: Yup.string()
.max(40, "Must be 40 characters or less")
.required("Required"),
body: Yup.string()
.required("Required"),
})}
onSubmit={formSubmit}
>
<Form className={classes.form}>
<MyTextInput
label="Title"
name="title"
type="text"
placeholder="title body"
value={title}
setValue={setTitle}
/>
<MyTextArea
label="Body"
name="body"
rows="6"
placeholder="Post body"
value={body}
setValue={setBody}
/>