Formmik:一個用來管理form 表單的 套件

可以幫助你

  1. Form state management(狀態管理): Formik helps you manage your form state by providing a single source of truth for your form data.
  2. Validation(驗證): Formik provides built-in support for validation using Yup (more on that later). You can also use custom validation functions.
  3. Error handling(錯誤處理): Formik makes it easy to handle errors and display error messages to the user.
  4. Submission handling(處理submit): Formik provides a simple way to handle form submissions, including handling async submissions and displaying loading indicators.

useCase:

const SigninForm = useFormik({
    initialValues: {
      password: '',
      username: '',
    },
    validationSchema: Yup.object({
      username: Yup.string().min(8, 'username minimum 8 characters').required('username is required'),
      password: Yup.string().min(8, 'password minimum 8 characters').required('password is required'),
    }),
    onsubmit: async values => {
      const {} = await userApi.signin(values)
      setErrorMessage(undefined)
      setIsLoginRequest(true)
      const { response, err } = await userApi.signin(values)
      setIsLoginRequest(true)
      if (response) {
        SigninForm.resetForm()
        dispatch(setUser(response))
        dispatch(setAuthModalOpen(false))
        toast.success('Sign in success')
      }

      if (err) setErrorMessage(err.message)
    },
  })
<Box component="form" onsubmit={SigninForm.handleSubmit}>
      <Stack spacing={3}>
        <TextField
          type="text"
          placeholder="username"
          name="username"
          fullWidth
          value={SigninForm.values.username}
          onChange={SigninForm.handleChange}
          color="success"
          error={SigninForm.touched.username && SigninForm.errors.username !== undefined}
          helperText={SigninForm.touched.username && SigninForm.errors.username}
        ></TextField>
        <TextField
          type="password"
          placeholder="password"
          name="password"
          fullWidth
          value={SigninForm.values.password}
          onChange={SigninForm.handleChange}
          color="success"
          error={SigninForm.touched.password && SigninForm.errors.password !== undefined}
          helperText={SigninForm.touched.password && SigninForm.errors.password}
        ></TextField>
      </Stack>
    </Box>

Yup 可以幫助你定義驗證條件和錯誤訊息

useCase在上面

toast 是一個罐頭訊息會在視窗內彈出