@material-ui/core#Alert TypeScript Examples

The following examples show how to use @material-ui/core#Alert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Layout.tsx    From storefront with MIT License 6 votes vote down vote up
Layout: React.FC = ({ children }) => {
  const { alerts, closeModal, displayModal, modalView, removeAlert } = useUI();

  return (
    <>
      <Header />
      <Box sx={{ display: 'flex', flexDirection: 'column' }}>{children}</Box>
      <Footer />
      <CookieBanner />
      <Dialog open={displayModal} onClose={closeModal}>
        <>{modalView === 'LOGIN_VIEW' && <LoginView />}</>
      </Dialog>
      {alerts.map((alert) => (
        <Snackbar
          key={alert.id}
          autoHideDuration={5000}
          open={alert.open}
          onClose={() => removeAlert(alert.id)}
        >
          <Alert {...alert.props} onClose={() => removeAlert(alert.id)}>
            {alert.message}
          </Alert>
        </Snackbar>
      ))}
    </>
  );
}
Example #2
Source File: LoginView.tsx    From storefront with MIT License 4 votes vote down vote up
LoginView: React.VFC = () => {
  const [alert, setAlert] = useState<string>();
  const { closeModal } = useUI();
  const [login, { loading }] = useLoginMutation();

  const { control, formState, handleSubmit } = useForm<LoginMutationVariables>({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = handleSubmit(async (variables) => {
    try {
      const { data } = await login({ variables });

      if (data?.login?.authToken != null) {
        localStorage.setItem('authToken', data.login.authToken);
      }
      if (data?.login?.refreshToken != null) {
        localStorage.setItem('refreshToken', data.login.refreshToken);
      }
      closeModal();
    } catch (error) {
      if (isApolloError(error)) {
        setAlert(error.graphQLErrors[0].message);
      }
    }
  });

  return (
    <>
      <Box sx={{ textAlign: 'center', mb: 6 }}>
        <Logo />
      </Box>
      <form onSubmit={onSubmit}>
        {alert && (
          <Box sx={{ mb: 2 }}>
            <Alert severity="error">{alert}</Alert>
          </Box>
        )}
        {/* Username or email */}
        <Controller
          control={control}
          name="username"
          render={({ field }) => (
            <TextField
              required
              autoCapitalize="off"
              autoCorrect="off"
              error={'username' in formState.errors}
              helperText={formState.errors.username?.message}
              label="Username or email"
              type="text"
              {...field}
            />
          )}
        />
        {/* Password */}
        <Controller
          control={control}
          name="password"
          render={({ field }) => (
            <TextField
              required
              error={'password' in formState.errors}
              helperText={formState.errors.password?.message}
              label="Password"
              type="password"
              {...field}
            />
          )}
        />
        <Box sx={{ mt: 1 }}>
          <Button fullWidth type="submit" color="primary" loading={loading}>
            Log in
          </Button>
        </Box>
        <Box sx={{ mt: 1, textAlign: 'center' }}>
          Don’t have an account? <Link href="/register">Register</Link>
        </Box>
      </form>
    </>
  );
}
Example #3
Source File: register.tsx    From storefront with MIT License 4 votes vote down vote up
Register: NextPage = () => {
  const [successMessage, setSuccessMessage] = useState<string>();
  const router = useRouter();
  const [registerUser, { loading }] = useRegisterMutation();
  const { addAlert } = useUI();

  /** Hide the Status bar on cross button click. */
  const handleCloseButtonClick = () => {
    // Remove the message.
    setSuccessMessage(undefined);
  };

  /**
   * Handle registration success.
   *
   * @param data Result data received
   */
  const handleRegisterUserSuccess = (data: RegisterMutation) => {
    if (data.registerUser?.user?.email != null) {
      // Add a message.
      setSuccessMessage('Registration Successful! You will be redirected to login page now...');

      setTimeout(() => {
        // Send the user to Login page.
        router.push('/login?registered=true');
      }, 3000);
    }
  };

  const { control, formState, handleSubmit } = useForm<RegisterFormData>({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = handleSubmit(async ({ email, password, username }) => {
    try {
      const { data } = await registerUser({
        variables: { email, password, username },
      });
      if (data != null) {
        handleRegisterUserSuccess(data);
      }
    } catch (error) {
      if (isApolloError(error)) {
        addAlert(error.graphQLErrors[0].message, { severity: 'error' });
      }
    }
  });

  return (
    <Layout>
      <Container maxWidth="sm">
        <Box sx={{ mt: 6, pt: 6 }}>
          <Typography gutterBottom variant="h2">
            Register
          </Typography>
          {/* Success Message */}
          {successMessage != null && (
            <Alert severity="success" onClose={handleCloseButtonClick}>
              {successMessage}
            </Alert>
          )}
          <form onSubmit={onSubmit}>
            {/* Username */}
            <Controller
              control={control}
              name="username"
              render={({ field }) => (
                <TextField
                  required
                  autoComplete="username"
                  error={'username' in formState.errors}
                  helperText={formState.errors.username?.message}
                  label="Username"
                  type="text"
                  {...field}
                />
              )}
            />
            {/* Email */}
            <Controller
              control={control}
              name="email"
              render={({ field }) => (
                <TextField
                  required
                  autoComplete="email"
                  error={'email' in formState.errors}
                  helperText={formState.errors.email?.message}
                  label="Email"
                  type="email"
                  {...field}
                />
              )}
            />
            {/* Password */}
            <Controller
              control={control}
              name="password"
              render={({ field }) => (
                <TextField
                  required
                  autoComplete="new-password"
                  error={'password' in formState.errors}
                  helperText={formState.errors.password?.message}
                  label="Password"
                  type="password"
                  {...field}
                />
              )}
            />
            <Box sx={{ mt: 2 }}>
              <Button type="submit" color="primary" loading={loading}>
                Register
              </Button>
            </Box>
          </form>
        </Box>
      </Container>
    </Layout>
  );
}