react-use#useAsync TypeScript Examples

The following examples show how to use react-use#useAsync. 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: AlertsSummary.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
AlertsSummary = ({ query }: { query: string }) => {
    const opsgenieApi = useApi(opsgenieApiRef);
    const { value, loading, error } = useAsync(async () => await opsgenieApi.getAlerts({limit: 3, query: query}));

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <AlertUI data-testid="error-message" severity="error">
                {error.message}
            </AlertUI>
        );
    }

    return (
        <AlertsSummaryTable alerts={value!} />
    );
}
Example #2
Source File: AlertsList.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
AlertsList = () => {
    const opsgenieApi = useApi(opsgenieApiRef);

    const { value, loading, error } = useAsync(async () => await opsgenieApi.getAlerts());

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <Alert data-testid="error-message" severity="error">
                {error.message}
            </Alert>
        );
    }

    return <AlertsTable alerts={value!} />;
}
Example #3
Source File: OnCallListCard.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
OnCallListCardContent = ({teamName}: OnCallListContentProps) => {
    const opsgenieApi = useApi(opsgenieApiRef);
    const { value, loading, error } = useAsync(async () => await opsgenieApi.getSchedulesForTeam(teamName));

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <Alert data-testid="error-message" severity="error">
                {error.message}
            </Alert>
        );
    }

    return (
        <div>
            {value!.filter(schedule => schedule.enabled).map(schedule => <OnCallForScheduleList key={schedule.id} schedule={schedule} />)}
        </div>
    );
}
Example #4
Source File: IncidentsList.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
IncidentsList = () => {
    const opsgenieApi = useApi(opsgenieApiRef);

    const {value, loading, error} = useAsync(async () => await opsgenieApi.getIncidents());

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <Alert data-testid="error-message" severity="error">
                {error.message}
            </Alert>
        );
    }

    return (
        <IncidentsTable incidents={value!} />
    );
}
Example #5
Source File: OnCallList.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
OnCallForScheduleList = ({ schedule }: { schedule: Schedule }) => {
    const opsgenieApi = useApi(opsgenieApiRef);
    const { value, loading, error } = useAsync(async () => await opsgenieApi.getOnCall(schedule.id));

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <Alert data-testid="error-message" severity="error">
                {error.message}
            </Alert>
        );
    }

    return (
        <List>
            {value!.map((responder, i) => (
                <ListItem key={i} button component="a" href={opsgenieApi.getUserDetailsURL(responder.id)}>
                    <ListItemIcon>
                        <PersonIcon />
                    </ListItemIcon>

                    <ListItemText primary={responder.name} />
                </ListItem>
            ))}

            {value!.length === 0 && <ListItem><ListItemText primary="⚠️ No one on-call." /></ListItem>}
        </List>
    );
}
Example #6
Source File: OnCallList.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
OnCallList = ({ cardsPerPage }: OnCallListProps) => {
    const opsgenieApi = useApi(opsgenieApiRef);
    const { value, loading, error } = useAsync(async () => await opsgenieApi.getSchedules());

    if (loading) {
        return <Progress />;
    } else if (error) {
        return (
            <Alert data-testid="error-message" severity="error">
                {error.message}
            </Alert>
        );
    }

    return <SchedulesGrid schedules={value!.filter(schedule => schedule.enabled)} cardsPerPage={cardsPerPage || 6} />;
}
Example #7
Source File: StakingStatus.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
StakingStatusProvider: FC = ({ children }) => {
  const [state, setState] = useState<State>(initialState)
  const [lockedV1, setLockedV1] = useFetchState<{
    balance: BigDecimal
    end: number
  }>()

  const networkAddresses = useNetworkAddresses()
  const signer = useSigner()
  const account = useOwnAccount()

  // TODO: Query via graphql instead (?)
  useAsync(async () => {
    if (!signer || !account || !!lockedV1?.value) return
    setLockedV1.fetching()
    const contract = IncentivisedVotingLockup__factory.connect(networkAddresses.vMTA, signer)
    const data = await contract.locked(account)
    const balance = new BigDecimal(data?.amount ?? 0)
    const end = (data?.end?.toNumber() ?? 0) * 1e3
    setLockedV1.value({ balance, end })
  }, [account, lockedV1, networkAddresses.vMTA, setLockedV1, signer])

  return providerFactory(
    dispatchContext,
    {
      value: {
        setSelectedOption: () => {
          setState({ ...state, hasSelectedStakeOption: true })
        },
        setWithdrewV1Balance: () => {
          setState({ ...state, hasWithdrawnV1Balance: true })
        },
      },
    },
    providerFactory(stateContext, { value: { ...state, lockedV1 } }, children),
  )
}
Example #8
Source File: NoteView.tsx    From joplin-utils with MIT License 6 votes vote down vote up
NoteView: React.FC = () => {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  const noteState = useAsync(async () => {
    const settings = await getSettings()
    if (!settings) {
      history.push('/')
      return
    }
    noteViewState.settings = settings
    config.token = settings.token
    config.port = settings.port
    const note = await noteApi.get(id, ['id', 'title', 'body'])
    document.title = JoplinNoteUtil.trimTitleStart(note.title)
    const resourceList = await noteApi.resourcesById(id)
    return {
      ...note,
      resourceList,
    } as RenderNote
  })

  async function onClick() {
    await noteActionApi.openAndWatch(id)
  }

  return (
    <div className={css.noteView}>
      <button onClick={onClick} className={css.control}>
        在编辑器中打开
      </button>
      <div>{noteState.value && <MarkdownView note={noteState.value} />}</div>
    </div>
  )
}
Example #9
Source File: Analytics.tsx    From backstage-plugin-opsgenie with MIT License 4 votes vote down vote up
Analytics = () => {
    const configApi = useApi(configApiRef);
    const opsgenieApi = useApi(opsgenieApiRef);

    const from = moment().subtract(1, 'year').startOf('quarter');
    const to = moment();

    const { value: data, loading, error } = useAsync(async () => {
        return Promise.all([
            opsgenieApi.getIncidents({
                limit: 100,
                query: `createdAt < ${to.valueOf()} AND createdAt > ${from.valueOf()}`
            }),
            opsgenieApi.getTeams(),
        ])
    });

    if (loading) {
        return <Progress />;
    } else if (error) {
        return <Alert severity="error">{error.message}</Alert>;
    }

    const context: Context = {
        from: from,
        to: to,
        incidents: data![0].filter(incident => moment(incident.impactStartDate).isAfter(from)),
        teams: data![1],
    };

    const businessHours = {
        start: configApi.getOptionalNumber('opsgenie.analytics.businessHours.start') || DEFAULT_BUSINESS_HOURS_START,
        end: configApi.getOptionalNumber('opsgenie.analytics.businessHours.end') || DEFAULT_BUSINESS_HOURS_END,
    };

    return (
        <Grid container spacing={3}>
            <Grid item xs={12}>
                <InfoPanel
                    title="This graphs cover one year worth of incidents, from the current quarter to the same quarter last year."
                    message={
                        <ul>
                            <li>Incidents from {from.format('LL')} to now are used</li>
                            <li>Business hours are {businessHours.start} to {businessHours.end}</li>
                            <li>Responders are read from the <code>responders</code> incident extra property if defined, or from the "responders" section of an incident.</li>
                        </ul>
                    }
                />
            </Grid>

            <Grid item md={6} xs={12}>
                <WeeklyIncidents context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <WeeklyIncidentsSeverity context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <WeeklyIncidentsResponders context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <MonthlyIncidentsResponders context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <QuarterlyIncidentsResponders context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <DailyIncidentsResponders context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <HourlyIncidents context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <DailyIncidents context={context} />
            </Grid>

            <Grid item md={6} xs={12}>
                <WeeklyImpactResponders context={context} />
            </Grid>
        </Grid>
    );
}
Example #10
Source File: SignupInvited.tsx    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
SingupInvitedPageUnconnected: FC<DispatchProps & ConnectedProps> = ({ code }) => {
  const [initFormModel, setInitFormModel] = useState<FormModel>();
  const [greeting, setGreeting] = useState<string>();
  const [invitedBy, setInvitedBy] = useState<string>();
  useAsync(async () => {
    const invite = await getBackendSrv().get('/api/user/invite/' + code);
    setInitFormModel({
      email: invite.email,
      name: invite.name,
      username: invite.email,
    });

    setGreeting(invite.name || invite.email || invite.username);
    setInvitedBy(invite.invitedBy);
  }, []);

  const onSubmit = async (formData: FormModel) => {
    await getBackendSrv().post('/api/user/invite/complete', { ...formData, inviteCode: code });
    window.location.href = getConfig().appSubUrl + '/';
  };

  return (
    <Page navModel={navModel}>
      <Page.Contents>
        <h3 className="page-sub-heading">Hello {greeting || 'there'}.</h3>

        <div className="modal-tagline p-b-2">
          <em>{invitedBy || 'Someone'}</em> has invited you to join Grafana and the organization{' '}
          <span className="highlight-word">{contextSrv.user.orgName}</span>
          <br />
          Please complete the following and choose a password to accept your invitation and continue:
        </div>
        <Forms.Form defaultValues={initFormModel} onSubmit={onSubmit}>
          {({ register, errors }) => (
            <>
              <Forms.Field invalid={!!errors.email} error={!!errors.email && errors.email.message} label="Email">
                <Forms.Input
                  size="md"
                  placeholder="[email protected]"
                  name="email"
                  ref={register({
                    required: 'Email is required',
                    pattern: {
                      value: /^\S+@\S+$/,
                      message: 'Email is invalid',
                    },
                  })}
                />
              </Forms.Field>
              <Forms.Field invalid={!!errors.name} error={!!errors.name && errors.name.message} label="Name">
                <Forms.Input size="md" placeholder="Name (optional)" name="name" ref={register} />
              </Forms.Field>
              <Forms.Field
                invalid={!!errors.username}
                error={!!errors.username && errors.username.message}
                label="Username"
              >
                <Forms.Input
                  size="md"
                  placeholder="Username"
                  name="username"
                  ref={register({ required: 'Username is required' })}
                />
              </Forms.Field>
              <Forms.Field
                invalid={!!errors.password}
                error={!!errors.password && errors.password.message}
                label="Password"
              >
                <Forms.Input
                  size="md"
                  type="password"
                  placeholder="Password"
                  name="password"
                  ref={register({ required: 'Password is required' })}
                />
              </Forms.Field>

              <Forms.Button type="submit">Sign Up</Forms.Button>
            </>
          )}
        </Forms.Form>
      </Page.Contents>
    </Page>
  );
}