react-use#useMount TypeScript Examples
The following examples show how to use
react-use#useMount.
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: app-selector.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
AppSelector = (props: IProps) => {
const { projectId: _projectId, autoSelect = false, getData: propsGetData, joined, ...rest } = props;
const pId = routeInfoStore.useStore((s) => s.params.projectId);
useMount(() => {
if (autoSelect && !rest.value) {
(propsGetData || getData)().then((res) => {
const curApp = res.list?.[0];
if (curApp) {
rest.onClickItem?.(curApp);
rest.onChange?.(curApp.id);
}
});
}
});
const projectId = _projectId || pId;
const getData = (_q: Obj = {}) => {
if (!projectId) return;
return joined
? getJoinedApps({ projectId: +projectId, ..._q } as any).then((res) => res.data)
: getApps({ projectId, ..._q } as any).then((res: any) => res.data);
};
return (
<LoadMoreSelector
getData={propsGetData || getData}
dropdownMatchSelectWidth={false}
placeholder={i18n.t('common:search by {name}', { name: i18n.t('application') })}
dataFormatter={({ list, total }) => ({
total,
list: map(list, (item) => ({ ...item, label: item.displayName || item.name, value: item.id })),
})}
optionRender={AppItem}
dropdownStyle={{ width: 400, height: 300 }}
chosenItemConvert={(v: IChosenItem[] | IChosenItem) => chosenItemConvert(v)}
{...rest}
/>
);
}
Example #2
Source File: _app.tsx From storefront with MIT License | 5 votes |
App: NextComponentType<AppContext, AppInitialProps, Props> = ({
apollo,
apolloState,
Component,
pageProps,
router,
}) => {
useMount(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
jssStyles?.parentNode?.removeChild(jssStyles);
ReactGA.initialize(process.env.GA_TRACKING_ID, {
debug: process.env.NODE_ENV === 'development',
});
ReactGA.plugin.require('ec');
ReactGA.pageview(router.asPath);
router.events.on('routeChangeComplete', (url: string) => {
ReactGA.pageview(url);
});
});
return (
<ApolloProvider client={apollo ?? createClient({ initialState: apolloState?.data })}>
<SettingsProvider>
<SettingsContext.Consumer>
{({ settings, seo }) => (
<>
<Head>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
{seo.webmaster?.googleVerify != null && (
<meta name="google-site-verification" content={seo.webmaster.googleVerify} />
)}
{seo.webmaster?.msVerify != null && (
<meta name="msvalidate.01" content={seo.webmaster.msVerify} />
)}
</Head>
<DefaultSeo
title={settings.title ?? undefined}
description={settings.description ?? undefined}
canonical={absoluteURL(router.asPath)}
openGraph={{
type: 'website',
locale: 'en_US',
url: absoluteURL(router.asPath),
site_name: settings.title ?? undefined,
}}
twitter={{
handle: '@artwithaliens',
cardType: 'summary_large_image',
}}
/>
</>
)}
</SettingsContext.Consumer>
<ManagedUIContext>
<CssBaseline />
<Component {...pageProps} />
</ManagedUIContext>
</SettingsProvider>
</ApolloProvider>
);
}
Example #3
Source File: datasource-selector.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
DataSourceSelector = (props: any) => {
const [options, setOptions] = React.useState([]);
const { projectId, dataSourceType, onChange, value, ...rest } = props;
useMount(() => {
getData();
});
const getData = () => {
if (projectId && dataSourceType) {
// 暂时只取测试环境的addon, Custom/AliCloud-Rds/AliCloud-Redis 为自定义类型,自定义类型暂为redis和mysql共享
dopStore
.getDataSourceAddons({
projectId,
displayName: [dataSourceTypeMap[dataSourceType], 'Custom', 'AliCloud-Rds', 'AliCloud-Redis'],
})
.then((res: any) => {
setOptions(
(res || []).map((item: any) => ({
value: item.instanceId,
label: `${item.name}${item.tag ? `(${item.tag})` : ''}`,
})),
);
});
}
};
useUpdateEffect(() => {
onChange(undefined);
getData();
}, [projectId, dataSourceType]);
const dataSourceOptionRender = (item: any) => {
return (
<Option key={item.value} value={item.value}>
<span className="ml-2" title={item.label}>
{item.label}
</span>
</Option>
);
};
return (
<Select
className="w-full"
notFoundContent={i18n.t('common:No data')}
showArrow={false}
showSearch
optionFilterProp="children"
onChange={onChange}
filterOption={(input: any, option: any) => {
return option.props.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}}
value={value}
placeholder={i18n.t('Please Select')}
{...rest}
>
{options.map(dataSourceOptionRender)}
</Select>
);
}
Example #4
Source File: LayoutView.tsx From joplin-utils with MIT License | 5 votes |
LayoutView: React.FC = () => {
const [language, setLanguage] = useLocalStorage<LanguageEnum>(
'language',
getLanguage(),
)
const [{ value: list }, fetch] = useAsyncFn(
async (language: LanguageEnum) => {
console.log('language: ', language)
await i18n.init({ en, zhCN }, language)
return routeList.map((item) => ({
...item,
title: i18n.t(item.title as any),
}))
},
[],
)
useMount(() => fetch(language!))
const [refreshKey, { inc }] = useCounter(0)
async function changeLanguage(value: LanguageEnum) {
setLanguage(value)
await fetch(value)
inc()
}
return (
<Layout className={css.app}>
<Layout.Sider className={css.sider} width="max-content">
<h2 className={css.logo}>Joplin Batch</h2>
<Menu>
{list &&
list.map((item) => (
<Menu.Item key={item.path as string}>
<Link to={item.path as string}>{item.title}</Link>
</Menu.Item>
))}
</Menu>
</Layout.Sider>
<Layout>
<Layout.Header className={css.header}>
<Select
options={[
{ label: 'English', value: LanguageEnum.En },
{ label: '中文', value: LanguageEnum.ZhCN },
]}
value={language}
onChange={changeLanguage}
/>
</Layout.Header>
<Layout.Content className={css.main}>
{list && <RouterView key={refreshKey} />}
</Layout.Content>
</Layout>
</Layout>
)
}
Example #5
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
PureFilter = (props: IPureFilterProps) => {
const {
filterTirgger = 'onChange',
connectUrlSearch = false,
updateSearch,
onFilter = noop,
query = {},
className = '',
formatFormData,
urlExtra,
...rest
} = props;
// const query = routeInfoStore.getState(s => s.query);
const filterRef: any = React.useRef(null as any);
useMount(() => {
const { pageNo: _, ...fieldsValue } = query;
// 关联url, 将query初始化到表单
if (connectUrlSearch && !isEmpty(fieldsValue)) {
setTimeout(() => {
setFieldsValue(fieldsValue);
}, 0);
} else if (filterTirgger === 'onChange') {
setTimeout(() => {
// 只能在setTimeout中拿到初始请求的值
const formData = filterRef.current?.form.getFieldsValue();
changeFilterData(formData);
}, 0);
}
});
React.useEffect(() => {
if (!isEmpty(urlExtra)) {
const filterForm = get(filterRef, 'current.form');
const filterData = filterForm ? filterForm.getFieldsValue() : {};
updateSearch({ ...urlExtra, ...filterData });
}
}, [updateSearch, urlExtra]);
const debounceFilter = debounce((filterData: Obj) => {
if (connectUrlSearch) {
updateSearch(filterData);
}
onFilter(filterData);
}, 1000);
// filter变化的时候调用
const changeFilterData = (filterData: Obj) => {
debounceFilter(filterData);
};
const setFieldsValue = (obj: Obj) => {
const filterForm = get(filterRef, 'current.form');
if (filterForm) {
const filterFields = filterForm.getFieldsValue();
const formValue = {};
map(filterFields, (_, _key) => has(obj, _key) && set(formValue, _key, obj[_key]));
filterForm.setFieldsValue(formatFormData ? formatFormData(formValue) : formValue);
changeFilterData(obj); // 带上除filter之外的其他参数,如pageNo
}
};
const filterProps = {
onChange: {
actions: [],
},
onSubmit: {},
};
return (
<BaseFilter
onSubmit={changeFilterData}
className={`dice-filter my-3 ${className}`}
{...rest}
{...(filterProps[filterTirgger] || {})}
ref={filterRef}
/>
);
}
Example #6
Source File: PaypalButton.tsx From storefront with MIT License | 4 votes |
PaypalButton: React.VFC<Props> = ({
cart,
disabled,
onAuthorize,
paymentClientToken,
shipping,
}) => {
const styles = useStyles();
const [loading, setLoading] = useState(true);
useMount(async () => {
if (process.browser && loading && document.querySelector('#paypal-button') != null) {
const braintree = await import('braintree-web');
const client = await createClient(paymentClientToken);
const paypalCheckout = await braintree.paypalCheckout.create({ client });
const env = process.env.NODE_ENV === 'production' ? 'production' : 'sandbox';
paypal.Button.render(
{
// @ts-ignore
env,
client: {
[env]: process.env.PAYPAL_CLIENT_ID,
},
locale: 'en_US',
style: {
// @ts-ignore
color: 'gold',
// @ts-ignore
label: 'pay',
// @ts-ignore
shape: 'pill',
// @ts-ignore
size: 'responsive',
tagline: false,
},
payment: () =>
paypalCheckout.createPayment({
// @ts-ignore
flow: 'checkout',
amount: cart.total == null ? undefined : parseFloat(cart.total),
currency: 'EUR',
enableShippingAddress: true,
shippingAddressEditable: false,
shippingAddressOverride: {
recipientName: `${shipping?.firstName} ${shipping?.lastName}`.trim(),
line1: shipping?.address1 ?? '',
line2: shipping?.address2 ?? '',
city: shipping?.city ?? '',
countryCode: shipping?.country ?? '',
postalCode: shipping?.postcode ?? '',
state: shipping?.state ?? '',
},
}),
// validate: () => {
// // We can enable or disable the button here, but without visual feedback
// actions.disable();
// },
onAuthorize: async (data) => {
const payload = await paypalCheckout.tokenizePayment(data);
onAuthorize(payload.nonce);
return payload;
},
onError: () => {
// Show an error page here, when an error occurs
},
},
'#paypal-button',
// @ts-ignore
// eslint-disable-next-line promise/prefer-await-to-then
).then(() => {
setLoading(false);
});
}
});
return (
<div className={clsx(styles.root, disabled && styles.disabled)} id="paypal-button">
{loading && (
<div className={styles.loader}>
<CircularProgress />
</div>
)}
</div>
);
}
Example #7
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 4 votes |
AlarmReport = () => {
const roleMap = memberStore.useStore((s) => s.roleMap);
const [reportTasks, reportTaskPaging, systemDashboards, reportTypes] = alarmReportStore.useStore((s) => [
s.reportTasks,
s.reportTaskPaging,
s.systemDashboards,
s.reportTypes,
]);
const {
createReportTask,
getReportTasks,
updateReportTask,
deleteReportTask,
switchReportTask,
getSystemDashboards,
getReportTypes,
} = alarmReportStore.effects;
const { getNotifyGroups } = notifyGroupStore.effects;
const notifyGroups = notifyGroupStore.useStore((s) => s.notifyGroups);
const [loading] = useLoading(alarmReportStore, ['getReportTasks']);
const orgId = orgStore.getState((s) => s.currentOrg.id);
const [activeGroupId, setActiveGroupId] = React.useState(0);
const [modalVisible, openModal, closeModal] = useSwitch(false);
const [{ editingTask, allChannelMethods }, updater] = useUpdate({
editingTask: {},
allChannelMethods: notifyChannelOptionsMap,
});
const channelMethods = getNotifyChannelMethods.useData() as Obj<string>;
const addNotificationGroupAuth = usePerm((s) => s.org.cmp.alarms.addNotificationGroup.pass); // 企业中心的添加通知组,需要验证权限,项目的暂无埋点
const { pageNo, pageSize, total } = reportTaskPaging;
useMount(() => {
getReportTasks({ pageNo, pageSize });
getReportTypes();
getSystemDashboards();
getNotifyGroups({ scopeType: 'org', scopeId: String(orgId), pageSize: 100 });
getNotifyChannelMethods.fetch();
});
React.useEffect(() => {
updater.allChannelMethods(getFinalNotifyChannelOptions(channelMethods, true));
}, [channelMethods, updater]);
const handleCloseModal = () => {
closeModal();
updater.editingTask({});
};
const getFieldsList = (form: FormInstance) => {
const activeGroup = find(notifyGroups, { id: activeGroupId });
const fieldsList = [
{
label: i18n.t('cmp:name-report'),
name: 'name',
itemProps: {
maxLength: 50,
},
},
{
label: i18n.t('cmp:Type'),
name: 'type',
type: 'radioGroup',
itemProps: { disabled: !isEmpty(editingTask) },
options: reportTypes,
initialValue: 'daily',
},
{
label: i18n.t('cmp:Report template'),
name: 'dashboardId',
type: 'select',
options: map(systemDashboards, ({ name, id }) => ({ name, value: id })),
initialValue: 'daily',
},
{
label: i18n.t('dop:select group'),
name: ['notifyTarget', 'groupId'],
getComp: () => (
<Select
onSelect={(id: number) => {
form.setFieldsValue({
notifyTarget: {
groupId: id,
groupType: [],
},
});
setActiveGroupId(id);
}}
dropdownRender={(menu) => (
<div>
{menu}
<Divider className="my-1" />
<div className="text-xs px-2 py-1 text-desc" onMouseDown={(e) => e.preventDefault()}>
<WithAuth pass={addNotificationGroupAuth}>
<span
className="hover-active"
onClick={() => {
goTo(goTo.pages.cmpNotifyGroup);
}}
>
{i18n.t('cmp:Add More Notification Groups')}
</span>
</WithAuth>
</div>
</div>
)}
>
{map(notifyGroups, ({ id, name }) => (
<Select.Option key={id} value={id}>
{name}
</Select.Option>
))}
</Select>
),
},
{
label: i18n.t('Notification method'),
name: ['notifyTarget', 'groupType'],
type: 'select',
initialValue: get(editingTask, 'notifyTarget.groupType'),
options: (activeGroup && allChannelMethods[activeGroup.targets[0].type]) || [],
itemProps: { mode: 'multiple' },
},
];
return fieldsList;
};
const handleDelete = (id: number) => {
confirm({
title: i18n.t('cmp:are you sure you want to delete this task?'),
content: i18n.t('cmp:the task will be permanently deleted'),
onOk() {
deleteReportTask(id);
},
});
};
const handleEdit = (item: COMMON_ALARM_REPORT.ReportTaskQuery) => {
const {
notifyTarget: { groupType, ...subRest },
...rest
} = item;
updater.editingTask({
notifyTarget: {
groupType: groupType.split(','),
...subRest,
},
...rest,
});
openModal();
};
const handleSubmit = ({ notifyTarget: { groupType, ...subRest }, ...rest }: any) => {
const payload = {
notifyTarget: {
type: 'notify_group',
groupType: groupType.join(','),
...subRest,
},
...rest,
};
if (!isEmpty(editingTask)) {
updateReportTask({ ...payload, id: editingTask.id });
} else {
createReportTask(payload);
}
closeModal();
};
const handlePageChange = (no: number) => {
getReportTasks({ pageNo: no, pageSize });
};
const columns: Array<ColumnProps<COMMON_ALARM_REPORT.ReportTask>> = [
{
title: i18n.t('cmp:name-report'),
dataIndex: 'name',
},
{
title: i18n.t('cmp:Type'),
dataIndex: 'type',
width: 100,
render: (text) => ReportTypeMap[text],
},
{
title: i18n.t('default:Notification target'),
dataIndex: 'notifyTarget',
className: 'notify-info',
render: (notifyTarget) => {
const targets = get(notifyTarget, 'notifyGroup.targets', []);
const tip = i18n.t('cmp:Notification group does not exist or has been remove. Please change one.');
return (
<div className="flex">
{isEmpty(targets) ? (
<Tooltip title={tip}>
<span className="text-sub">{tip}</span>
</Tooltip>
) : (
<ListTargets roleMap={roleMap} targets={targets} />
)}
</div>
);
},
},
{
title: i18n.t('Creation time'),
dataIndex: 'createdAt',
width: 180,
render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
},
];
const actions = {
render: (record: COMMON_ALARM_REPORT.ReportTask) => {
return [
{
title: i18n.t('Edit'),
onClick: () => {
handleEdit(record);
},
},
{
title: i18n.t('Delete'),
onClick: () => {
handleDelete(record.id);
},
},
{
title: record.enable ? i18n.t('close') : i18n.t('Enable-open'),
onClick: () => {
switchReportTask({
id: record.id,
enable: !record.enable,
});
},
},
];
},
};
return (
<>
<TopButtonGroup>
<Button
type="primary"
onClick={() => {
openModal();
}}
>
{i18n.t('cmp:Add-report-task')}
</Button>
<FormModal
visible={modalVisible}
onCancel={handleCloseModal}
name={i18n.t('report task')}
fieldsList={getFieldsList}
formData={editingTask}
modalProps={{ destroyOnClose: true }}
onOk={handleSubmit}
/>
</TopButtonGroup>
<Spin spinning={loading}>
<ErdaTable
rowKey="id"
className="common-notify-list"
dataSource={reportTasks}
columns={columns}
actions={actions}
pagination={{
current: pageNo,
pageSize,
total,
onChange: handlePageChange,
}}
onRow={({ id }: COMMON_ALARM_REPORT.ReportTask) => {
return {
onClick: () => {
goTo(`./${id}`);
},
};
}}
scroll={{ x: '100%' }}
/>
</Spin>
</>
);
}