简体   繁体   中英

why input of formik form in material-ui dont work?

I use Axios and call API for my value of input, even though I set enableReinitialize: true, but

  1. when I want to change my input, it doesn't work
  2. yup validation doesn't work

how can I fix these 2 problems?

    const validationSchema = yup.object({
      email: yup
        .string("Enter your email")
        .email("Enter a valid email")
        .required("Email is required"),
      password: yup
        .string("Enter your password")
        .min(8, "Password should be of minimum 8 characters length")
        .required("Password is required"),
    });
    
    const FormOfFactors = () => {
      const [Industry, setIndustry] = useState();
      const params = useParams();
    
      useEffect(() => {
        async function fetchMyAPI() {
          let response = await axios.get(
            "http://nahoor.af:8080/nahoor/company/" + params.id,
          );
          setIndustry(response.data);
        }
    
        fetchMyAPI();
      }, []);
      const formik = useFormik({
        initialValues: {
          Industry,
        },
        validationSchema: validationSchema,
        onSubmit: (values) => {
          alert(JSON.stringify(values, null, 2));
          console.log("bebin dorost shod?!", values);
        },
        enableReinitialize: true,
      });
    
      return (
        <div>
          <form onSubmit={formik.handleSubmit}>
            <TextField
              fullWidth
              variant="outlined"
              id="email"
              name="email"
              label="Email"
              value={formik.values.Industry?.email}
              onChange={formik.handleChange}
              error={formik.touched.email && Boolean(formik.errors.email)}
              helperText={formik.touched.email && formik.errors.email}
            />
            <TextField
              fullWidth
              variant="outlined"
              id="password"
              name="password"
              label="Password"
              type="password"
              value={formik.values.password}
              onChange={formik.handleChange}
              error={formik.touched.password && Boolean(formik.errors.password)}
              helperText={formik.touched.password && formik.errors.password}
            />
            <Button color="primary" variant="contained" fullWidth type="submit">
              Submit
            </Button>
          </form>
        </div>
      );
    };
    
    export default FormOfFactors;

Define all your states inside Industry state with name of each field in name props in each text field and for each onChange use onChange = {(e)=>formik.seFieldValue("stateName",e.target.value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM