react-async-hook library provides useAsyncCallback that does the same thing as useMutation

This commit is contained in:
Athou
2022-08-13 18:38:11 +02:00
parent 6c6cc8d85b
commit 906acb217a
15 changed files with 122 additions and 152 deletions

View File

@@ -35,7 +35,7 @@
"react-hooks/exhaustive-deps": [ "react-hooks/exhaustive-deps": [
"warn", "warn",
{ {
"additionalHooks": "useAsync" "additionalHooks": "(^useAsync$)"
} }
], ],
@@ -67,8 +67,9 @@
"useState", "useState",
"useAppSelector", "useAppSelector",
"useAppDispatch", "useAppDispatch",
"useAsync",
"useForm", "useForm",
"useMutation", "useAsyncCallback",
"useCallback", "useCallback",
"useEffect" "useEffect"
] ]

View File

@@ -32,8 +32,7 @@
"react-infinite-scroller": "^1.2.6", "react-infinite-scroller": "^1.2.6",
"react-redux": "^8.0.2", "react-redux": "^8.0.2",
"react-router-dom": "^6.3.0", "react-router-dom": "^6.3.0",
"tinycon": "^0.6.8", "tinycon": "^0.6.8"
"use-mutation": "^2.2.1"
}, },
"devDependencies": { "devDependencies": {
"@lingui/cli": "^3.14.0", "@lingui/cli": "^3.14.0",
@@ -8490,31 +8489,6 @@
} }
} }
}, },
"node_modules/use-mutation": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/use-mutation/-/use-mutation-2.2.1.tgz",
"integrity": "sha512-qGvtQpVgj2Ekcrrykiq4rOlOhUrlebaO/sVVGpXjrb0IEOBtZqNzq8hKJwrYGkyUWqu3pBPpOEyss8OHRhS3Ow==",
"dependencies": {
"use-safe-callback": "^1.0.2"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16"
}
},
"node_modules/use-safe-callback": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/use-safe-callback/-/use-safe-callback-1.0.2.tgz",
"integrity": "sha512-RVeoyxgjJNfu9baNwulBM+HuPQGlcE1MJtrA1w50B5Hd0tyeKvrBIPdCfRx4Trrrxe34M6qRTys/bfpqsKRcyA==",
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16"
}
},
"node_modules/use-sync-external-store": { "node_modules/use-sync-external-store": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
@@ -14903,20 +14877,6 @@
"use-isomorphic-layout-effect": "^1.1.1" "use-isomorphic-layout-effect": "^1.1.1"
} }
}, },
"use-mutation": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/use-mutation/-/use-mutation-2.2.1.tgz",
"integrity": "sha512-qGvtQpVgj2Ekcrrykiq4rOlOhUrlebaO/sVVGpXjrb0IEOBtZqNzq8hKJwrYGkyUWqu3pBPpOEyss8OHRhS3Ow==",
"requires": {
"use-safe-callback": "^1.0.2"
}
},
"use-safe-callback": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/use-safe-callback/-/use-safe-callback-1.0.2.tgz",
"integrity": "sha512-RVeoyxgjJNfu9baNwulBM+HuPQGlcE1MJtrA1w50B5Hd0tyeKvrBIPdCfRx4Trrrxe34M6qRTys/bfpqsKRcyA==",
"requires": {}
},
"use-sync-external-store": { "use-sync-external-store": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",

View File

@@ -39,8 +39,7 @@
"react-infinite-scroller": "^1.2.6", "react-infinite-scroller": "^1.2.6",
"react-redux": "^8.0.2", "react-redux": "^8.0.2",
"react-router-dom": "^6.3.0", "react-router-dom": "^6.3.0",
"tinycon": "^0.6.8", "tinycon": "^0.6.8"
"use-mutation": "^2.2.1"
}, },
"devDependencies": { "devDependencies": {
"@lingui/cli": "^3.14.0", "@lingui/cli": "^3.14.0",

View File

@@ -101,5 +101,3 @@ export const errorToStrings = (err: any) => {
return strings return strings
} }
export const errorsToStrings = (errors: any[]) => errors.map(errorToStrings).flat()

View File

@@ -4,8 +4,8 @@ import { useForm } from "@mantine/form"
import { client, errorToStrings } from "app/client" import { client, errorToStrings } from "app/client"
import { UserModel } from "app/types" import { UserModel } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { useAsyncCallback } from "react-async-hook"
import { TbDeviceFloppy } from "react-icons/tb" import { TbDeviceFloppy } from "react-icons/tb"
import useMutation from "use-mutation"
interface UserEditProps { interface UserEditProps {
user?: UserModel user?: UserModel
@@ -17,18 +17,17 @@ export function UserEdit(props: UserEditProps) {
const form = useForm<UserModel>({ const form = useForm<UserModel>({
initialValues: props.user ?? ({ enabled: true } as UserModel), initialValues: props.user ?? ({ enabled: true } as UserModel),
}) })
const [saveUser, saveUserResult] = useMutation(client.admin.saveUser, { onSuccess: props.onSave }) const saveUser = useAsyncCallback(client.admin.saveUser, { onSuccess: props.onSave })
const errors = errorToStrings(saveUserResult.error)
return ( return (
<> <>
{errors.length > 0 && ( {saveUser.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(saveUser.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(saveUser)}> <form onSubmit={form.onSubmit(saveUser.execute)}>
<Stack> <Stack>
<TextInput label={t`Name`} {...form.getInputProps("name")} required /> <TextInput label={t`Name`} {...form.getInputProps("name")} required />
<PasswordInput label={t`Password`} {...form.getInputProps("password")} required={!props.user} /> <PasswordInput label={t`Password`} {...form.getInputProps("password")} required={!props.user} />
@@ -40,7 +39,7 @@ export function UserEdit(props: UserEditProps) {
<Button variant="default" onClick={props.onCancel}> <Button variant="default" onClick={props.onCancel}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={saveUserResult.status === "running"}> <Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={saveUser.loading}>
<Trans>Save</Trans> <Trans>Save</Trans>
</Button> </Button>
</Group> </Group>

View File

@@ -7,8 +7,8 @@ import { reloadTree } from "app/slices/tree"
import { useAppDispatch } from "app/store" import { useAppDispatch } from "app/store"
import { AddCategoryRequest } from "app/types" import { AddCategoryRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { useAsyncCallback } from "react-async-hook"
import { TbFolderPlus } from "react-icons/tb" import { TbFolderPlus } from "react-icons/tb"
import useMutation from "use-mutation"
import { CategorySelect } from "./CategorySelect" import { CategorySelect } from "./CategorySelect"
export function AddCategory() { export function AddCategory() {
@@ -16,23 +16,22 @@ export function AddCategory() {
const form = useForm<AddCategoryRequest>() const form = useForm<AddCategoryRequest>()
const [addCategory, addCategoryResult] = useMutation(client.category.add, { const addCategory = useAsyncCallback(client.category.add, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToSelectedSource()) dispatch(redirectToSelectedSource())
}, },
}) })
const errors = errorToStrings(addCategoryResult.error)
return ( return (
<> <>
{errors.length > 0 && ( {addCategory.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(addCategory.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(addCategory)}> <form onSubmit={form.onSubmit(addCategory.execute)}>
<Stack> <Stack>
<TextInput label={t`Category`} placeholder={t`Category`} {...form.getInputProps("name")} required /> <TextInput label={t`Category`} placeholder={t`Category`} {...form.getInputProps("name")} required />
<CategorySelect label={t`Parent`} {...form.getInputProps("parentId")} clearable /> <CategorySelect label={t`Parent`} {...form.getInputProps("parentId")} clearable />
@@ -40,7 +39,7 @@ export function AddCategory() {
<Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}> <Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbFolderPlus size={16} />} loading={addCategoryResult.status === "running"}> <Button type="submit" leftIcon={<TbFolderPlus size={16} />} loading={addCategory.loading}>
<Trans>Add</Trans> <Trans>Add</Trans>
</Button> </Button>
</Group> </Group>

View File

@@ -6,8 +6,8 @@ import { redirectToSelectedSource } from "app/slices/redirect"
import { reloadTree } from "app/slices/tree" import { reloadTree } from "app/slices/tree"
import { useAppDispatch } from "app/store" import { useAppDispatch } from "app/store"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { useAsyncCallback } from "react-async-hook"
import { TbFileImport } from "react-icons/tb" import { TbFileImport } from "react-icons/tb"
import useMutation from "use-mutation"
export function ImportOpml() { export function ImportOpml() {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -18,23 +18,22 @@ export function ImportOpml() {
}, },
}) })
const [importOpml, importOpmlResult] = useMutation(client.feed.importOpml, { const importOpml = useAsyncCallback(client.feed.importOpml, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToSelectedSource()) dispatch(redirectToSelectedSource())
}, },
}) })
const errors = errorToStrings(importOpmlResult.error)
return ( return (
<> <>
{errors.length > 0 && ( {importOpml.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(importOpml.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(v => importOpml(v.file))}> <form onSubmit={form.onSubmit(v => importOpml.execute(v.file))}>
<Stack> <Stack>
<FileInput <FileInput
label={t`OPML file`} label={t`OPML file`}
@@ -48,7 +47,7 @@ export function ImportOpml() {
<Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}> <Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbFileImport size={16} />} loading={importOpmlResult.status === "running"}> <Button type="submit" leftIcon={<TbFileImport size={16} />} loading={importOpml.loading}>
<Trans>Import</Trans> <Trans>Import</Trans>
</Button> </Button>
</Group> </Group>

View File

@@ -1,7 +1,7 @@
import { t, Trans } from "@lingui/macro" import { t, Trans } from "@lingui/macro"
import { Box, Button, Group, Stack, Stepper, TextInput } from "@mantine/core" import { Box, Button, Group, Stack, Stepper, TextInput } from "@mantine/core"
import { useForm } from "@mantine/form" import { useForm } from "@mantine/form"
import { client, errorsToStrings, errorToStrings } from "app/client" import { client, errorToStrings } from "app/client"
import { Constants } from "app/constants" import { Constants } from "app/constants"
import { redirectToFeed, redirectToSelectedSource } from "app/slices/redirect" import { redirectToFeed, redirectToSelectedSource } from "app/slices/redirect"
import { reloadTree } from "app/slices/tree" import { reloadTree } from "app/slices/tree"
@@ -9,8 +9,8 @@ import { useAppDispatch } from "app/store"
import { FeedInfoRequest, SubscribeRequest } from "app/types" import { FeedInfoRequest, SubscribeRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { useState } from "react" import { useState } from "react"
import { useAsyncCallback } from "react-async-hook"
import { TbRss } from "react-icons/tb" import { TbRss } from "react-icons/tb"
import useMutation from "use-mutation"
import { CategorySelect } from "./CategorySelect" import { CategorySelect } from "./CategorySelect"
export function Subscribe() { export function Subscribe() {
@@ -31,20 +31,19 @@ export function Subscribe() {
}, },
}) })
const [fetchFeed, fetchFeedResult] = useMutation(client.feed.fetchFeed, { const fetchFeed = useAsyncCallback(client.feed.fetchFeed, {
onSuccess: ({ data }) => { onSuccess: ({ data }) => {
step1Form.setFieldValue("url", data.data.url) step1Form.setFieldValue("url", data.url)
step1Form.setFieldValue("title", data.data.title) step1Form.setFieldValue("title", data.title)
setActiveStep(step => step + 1) setActiveStep(step => step + 1)
}, },
}) })
const [subscribe, subscribeResult] = useMutation(client.feed.subscribe, { const subscribe = useAsyncCallback(client.feed.subscribe, {
onSuccess: sub => { onSuccess: sub => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToFeed(sub.data.data.id)) dispatch(redirectToFeed(sub.data.id))
}, },
}) })
const errors = errorsToStrings([fetchFeedResult.error, errorToStrings(subscribeResult.error)])
const previousStep = () => { const previousStep = () => {
if (activeStep === 0) dispatch(redirectToSelectedSource()) if (activeStep === 0) dispatch(redirectToSelectedSource())
@@ -52,17 +51,23 @@ export function Subscribe() {
} }
const nextStep = (e: React.FormEvent<HTMLFormElement>) => { const nextStep = (e: React.FormEvent<HTMLFormElement>) => {
if (activeStep === 0) { if (activeStep === 0) {
step0Form.onSubmit(fetchFeed)(e) step0Form.onSubmit(fetchFeed.execute)(e)
} else if (activeStep === 1) { } else if (activeStep === 1) {
step1Form.onSubmit(subscribe)(e) step1Form.onSubmit(subscribe.execute)(e)
} }
} }
return ( return (
<> <>
{errors.length > 0 && ( {fetchFeed.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(fetchFeed.error)} />
</Box>
)}
{subscribe.error && (
<Box mb="md">
<Alert messages={errorToStrings(subscribe.error)} />
</Box> </Box>
)} )}
@@ -96,16 +101,12 @@ export function Subscribe() {
<Trans>Back</Trans> <Trans>Back</Trans>
</Button> </Button>
{activeStep === 0 && ( {activeStep === 0 && (
<Button type="submit" loading={fetchFeedResult.status === "running"}> <Button type="submit" loading={fetchFeed.loading}>
<Trans>Next</Trans> <Trans>Next</Trans>
</Button> </Button>
)} )}
{activeStep === 1 && ( {activeStep === 1 && (
<Button <Button type="submit" leftIcon={<TbRss size={16} />} loading={fetchFeed.loading || subscribe.loading}>
type="submit"
leftIcon={<TbRss size={16} />}
loading={fetchFeedResult.status === "running" || subscribeResult.status === "running"}
>
<Trans>Subscribe</Trans> <Trans>Subscribe</Trans>
</Button> </Button>
)} )}

View File

@@ -2,15 +2,15 @@ import { t, Trans } from "@lingui/macro"
import { Anchor, Box, Button, Checkbox, Divider, Group, Input, PasswordInput, Stack, Text, TextInput } from "@mantine/core" import { Anchor, Box, Button, Checkbox, Divider, Group, Input, PasswordInput, Stack, Text, TextInput } from "@mantine/core"
import { useForm } from "@mantine/form" import { useForm } from "@mantine/form"
import { openConfirmModal } from "@mantine/modals" import { openConfirmModal } from "@mantine/modals"
import { client, errorsToStrings } from "app/client" import { client, errorToStrings } from "app/client"
import { redirectToLogin, redirectToSelectedSource } from "app/slices/redirect" import { redirectToLogin, redirectToSelectedSource } from "app/slices/redirect"
import { reloadProfile } from "app/slices/user" import { reloadProfile } from "app/slices/user"
import { useAppDispatch, useAppSelector } from "app/store" import { useAppDispatch, useAppSelector } from "app/store"
import { ProfileModificationRequest } from "app/types" import { ProfileModificationRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { useEffect } from "react" import { useEffect } from "react"
import { useAsyncCallback } from "react-async-hook"
import { TbDeviceFloppy, TbTrash } from "react-icons/tb" import { TbDeviceFloppy, TbTrash } from "react-icons/tb"
import useMutation from "use-mutation"
interface FormData extends ProfileModificationRequest { interface FormData extends ProfileModificationRequest {
newPasswordConfirmation?: string newPasswordConfirmation?: string
@@ -27,18 +27,17 @@ export function ProfileSettings() {
}) })
const { setValues } = form const { setValues } = form
const [saveProfile, saveProfileResult] = useMutation(client.user.saveProfile, { const saveProfile = useAsyncCallback(client.user.saveProfile, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadProfile()) dispatch(reloadProfile())
dispatch(redirectToSelectedSource()) dispatch(redirectToSelectedSource())
}, },
}) })
const [deleteProfile, deleteProfileResult] = useMutation(client.user.deleteProfile, { const deleteProfile = useAsyncCallback(client.user.deleteProfile, {
onSuccess: () => { onSuccess: () => {
dispatch(redirectToLogin()) dispatch(redirectToLogin())
}, },
}) })
const errors = errorsToStrings([saveProfileResult.error, deleteProfileResult.error])
const openDeleteProfileModal = () => const openDeleteProfileModal = () =>
openConfirmModal({ openConfirmModal({
@@ -50,7 +49,7 @@ export function ProfileSettings() {
), ),
labels: { confirm: t`Confirm`, cancel: t`Cancel` }, labels: { confirm: t`Confirm`, cancel: t`Cancel` },
confirmProps: { color: "red" }, confirmProps: { color: "red" },
onConfirm: () => deleteProfile({}), onConfirm: () => deleteProfile.execute(),
}) })
useEffect(() => { useEffect(() => {
@@ -64,13 +63,19 @@ export function ProfileSettings() {
return ( return (
<> <>
{errors.length > 0 && ( {saveProfile.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(saveProfile.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(saveProfile)}> {deleteProfile.error && (
<Box mb="md">
<Alert messages={errorToStrings(deleteProfile.error)} />
</Box>
)}
<form onSubmit={form.onSubmit(saveProfile.execute)}>
<Stack> <Stack>
<Input.Wrapper label={t`User name`}> <Input.Wrapper label={t`User name`}>
<Box>{profile?.name}</Box> <Box>{profile?.name}</Box>
@@ -105,7 +110,7 @@ export function ProfileSettings() {
<Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}> <Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={saveProfileResult.status === "running"}> <Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={saveProfile.loading}>
<Trans>Save</Trans> <Trans>Save</Trans>
</Button> </Button>
<Divider orientation="vertical" /> <Divider orientation="vertical" />
@@ -113,7 +118,7 @@ export function ProfileSettings() {
color="red" color="red"
leftIcon={<TbTrash size={16} />} leftIcon={<TbTrash size={16} />}
onClick={() => openDeleteProfileModal()} onClick={() => openDeleteProfileModal()}
loading={deleteProfileResult.status === "running"} loading={deleteProfile.loading}
> >
<Trans>Delete account</Trans> <Trans>Delete account</Trans>
</Button> </Button>

View File

@@ -7,9 +7,8 @@ import { UserEdit } from "components/admin/UserEdit"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { Loader } from "components/Loader" import { Loader } from "components/Loader"
import { RelativeDate } from "components/RelativeDate" import { RelativeDate } from "components/RelativeDate"
import { useAsync } from "react-async-hook" import { useAsync, useAsyncCallback } from "react-async-hook"
import { TbCheck, TbPencil, TbPlus, TbTrash, TbX } from "react-icons/tb" import { TbCheck, TbPencil, TbPlus, TbTrash, TbX } from "react-icons/tb"
import useMutation from "use-mutation"
function BooleanIcon({ value }: { value: boolean }) { function BooleanIcon({ value }: { value: boolean }) {
return value ? <TbCheck size={18} /> : <TbX size={18} /> return value ? <TbCheck size={18} /> : <TbX size={18} />
@@ -20,13 +19,12 @@ export function AdminUsersPage() {
const query = useAsync(() => client.admin.getAllUsers(), []) const query = useAsync(() => client.admin.getAllUsers(), [])
const users = query.result?.data.sort((a, b) => a.id - b.id) const users = query.result?.data.sort((a, b) => a.id - b.id)
const [deleteUser, deleteUserResult] = useMutation(client.admin.deleteUser, { const deleteUser = useAsyncCallback(client.admin.deleteUser, {
onSuccess: () => { onSuccess: () => {
query.execute() query.execute()
closeAllModals() closeAllModals()
}, },
}) })
const errors = errorToStrings(deleteUserResult.error)
const openUserEditModal = (title: string, user?: UserModel) => { const openUserEditModal = (title: string, user?: UserModel) => {
openModal({ openModal({
@@ -57,7 +55,7 @@ export function AdminUsersPage() {
), ),
labels: { confirm: t`Confirm`, cancel: t`Cancel` }, labels: { confirm: t`Confirm`, cancel: t`Cancel` },
confirmProps: { color: "red" }, confirmProps: { color: "red" },
onConfirm: () => deleteUser({ id: user.id }), onConfirm: () => deleteUser.execute({ id: user.id }),
}) })
} }
@@ -73,9 +71,9 @@ export function AdminUsersPage() {
</Group> </Group>
</Title> </Title>
{errors.length > 0 && ( {deleteUser.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(deleteUser.error)} />
</Box> </Box>
)} )}
@@ -134,7 +132,7 @@ export function AdminUsersPage() {
<ActionIcon <ActionIcon
color={theme.primaryColor} color={theme.primaryColor}
onClick={() => openUserDeleteModal(u)} onClick={() => openUserDeleteModal(u)}
loading={deleteUserResult.status === "running"} loading={deleteUser.loading}
> >
<TbTrash size={18} /> <TbTrash size={18} />
</ActionIcon> </ActionIcon>

View File

@@ -13,35 +13,34 @@ import { Alert } from "components/Alert"
import { CategorySelect } from "components/content/add/CategorySelect" import { CategorySelect } from "components/content/add/CategorySelect"
import { Loader } from "components/Loader" import { Loader } from "components/Loader"
import { useEffect } from "react" import { useEffect } from "react"
import { useAsync } from "react-async-hook" import { useAsync, useAsyncCallback } from "react-async-hook"
import { TbDeviceFloppy, TbTrash } from "react-icons/tb" import { TbDeviceFloppy, TbTrash } from "react-icons/tb"
import { useParams } from "react-router-dom" import { useParams } from "react-router-dom"
import useMutation from "use-mutation"
export function CategoryDetailsPage() { export function CategoryDetailsPage() {
const { id = Constants.categoryIds.all } = useParams() const { id = Constants.categoryIds.all } = useParams()
const apiKey = useAppSelector(state => state.user.profile?.apiKey) const apiKey = useAppSelector(state => state.user.profile?.apiKey)
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const query = useAsync(() => client.category.getRoot(), []) const query = useAsync(() => client.category.getRoot(), [])
const category = query.result && flattenCategoryTree(query.result.data).find(c => c.id === id) const category = query.result && flattenCategoryTree(query.result.data).find(c => c.id === id)
const form = useForm<CategoryModificationRequest>() const form = useForm<CategoryModificationRequest>()
const { setValues } = form const { setValues } = form
const [modify, modifyResult] = useMutation(client.category.modify, { const modifyCategory = useAsyncCallback(client.category.modify, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToSelectedSource()) dispatch(redirectToSelectedSource())
}, },
}) })
const [deleteCategory, deleteCategoryResult] = useMutation(client.category.delete, { const deleteCategory = useAsyncCallback(client.category.delete, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToRootCategory()) dispatch(redirectToRootCategory())
}, },
}) })
const errors = [...errorToStrings(modifyResult.error), ...errorToStrings(deleteCategoryResult.error)]
const openDeleteCategoryModal = () => { const openDeleteCategoryModal = () => {
const categoryName = category?.name const categoryName = category?.name
@@ -56,7 +55,7 @@ export function CategoryDetailsPage() {
), ),
labels: { confirm: t`Confirm`, cancel: t`Cancel` }, labels: { confirm: t`Confirm`, cancel: t`Cancel` },
confirmProps: { color: "red" }, confirmProps: { color: "red" },
onConfirm: () => deleteCategory({ id: +id }), onConfirm: () => deleteCategory.execute({ id: +id }),
}) })
} }
@@ -73,13 +72,19 @@ export function CategoryDetailsPage() {
if (!category) return <Loader /> if (!category) return <Loader />
return ( return (
<Container> <Container>
{errors.length > 0 && ( {modifyCategory.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(modifyCategory.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(modify)}> {deleteCategory.error && (
<Box mb="md">
<Alert messages={errorToStrings(deleteCategory.error)} />
</Box>
)}
<form onSubmit={form.onSubmit(modifyCategory.execute)}>
<Stack> <Stack>
<Title order={3}>{category.name}</Title> <Title order={3}>{category.name}</Title>
<Input.Wrapper label={t`Generated feed url`}> <Input.Wrapper label={t`Generated feed url`}>
@@ -105,7 +110,7 @@ export function CategoryDetailsPage() {
<Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}> <Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={modifyResult.status === "running"}> <Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={modifyCategory.loading}>
<Trans>Save</Trans> <Trans>Save</Trans>
</Button> </Button>
<Divider orientation="vertical" /> <Divider orientation="vertical" />
@@ -113,7 +118,7 @@ export function CategoryDetailsPage() {
color="red" color="red"
leftIcon={<TbTrash size={16} />} leftIcon={<TbTrash size={16} />}
onClick={() => openDeleteCategoryModal()} onClick={() => openDeleteCategoryModal()}
loading={deleteCategoryResult.status === "running"} loading={deleteCategory.loading}
> >
<Trans>Delete</Trans> <Trans>Delete</Trans>
</Button> </Button>

View File

@@ -2,7 +2,7 @@ import { t, Trans } from "@lingui/macro"
import { Anchor, Box, Button, Code, Container, Divider, Group, Input, NumberInput, Stack, Text, TextInput, Title } from "@mantine/core" import { Anchor, Box, Button, Code, Container, Divider, Group, Input, NumberInput, Stack, Text, TextInput, Title } from "@mantine/core"
import { useForm } from "@mantine/form" import { useForm } from "@mantine/form"
import { openConfirmModal } from "@mantine/modals" import { openConfirmModal } from "@mantine/modals"
import { client, errorsToStrings } from "app/client" import { client, errorToStrings } from "app/client"
import { redirectToRootCategory, redirectToSelectedSource } from "app/slices/redirect" import { redirectToRootCategory, redirectToSelectedSource } from "app/slices/redirect"
import { reloadTree } from "app/slices/tree" import { reloadTree } from "app/slices/tree"
import { useAppDispatch, useAppSelector } from "app/store" import { useAppDispatch, useAppSelector } from "app/store"
@@ -12,10 +12,9 @@ import { CategorySelect } from "components/content/add/CategorySelect"
import { Loader } from "components/Loader" import { Loader } from "components/Loader"
import { RelativeDate } from "components/RelativeDate" import { RelativeDate } from "components/RelativeDate"
import { useEffect } from "react" import { useEffect } from "react"
import { useAsync } from "react-async-hook" import { useAsync, useAsyncCallback } from "react-async-hook"
import { TbDeviceFloppy, TbTrash } from "react-icons/tb" import { TbDeviceFloppy, TbTrash } from "react-icons/tb"
import { useParams } from "react-router-dom" import { useParams } from "react-router-dom"
import useMutation from "use-mutation"
function FilteringExpressionDescription() { function FilteringExpressionDescription() {
const example = <Code>url.contains('youtube') or (author eq 'athou' and title.contains('github')</Code> const example = <Code>url.contains('youtube') or (author eq 'athou' and title.contains('github')</Code>
@@ -60,19 +59,18 @@ export function FeedDetailsPage() {
const form = useForm<FeedModificationRequest>() const form = useForm<FeedModificationRequest>()
const { setValues } = form const { setValues } = form
const [modify, modifyResult] = useMutation(client.feed.modify, { const modifyFeed = useAsyncCallback(client.feed.modify, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToSelectedSource()) dispatch(redirectToSelectedSource())
}, },
}) })
const [unsubscribe, unsubscribeResult] = useMutation(client.feed.unsubscribe, { const unsubscribe = useAsyncCallback(client.feed.unsubscribe, {
onSuccess: () => { onSuccess: () => {
dispatch(reloadTree()) dispatch(reloadTree())
dispatch(redirectToRootCategory()) dispatch(redirectToRootCategory())
}, },
}) })
const errors = errorsToStrings([modifyResult.error, unsubscribeResult.error])
const openUnsubscribeModal = () => { const openUnsubscribeModal = () => {
const feedName = feed?.name const feedName = feed?.name
@@ -87,7 +85,7 @@ export function FeedDetailsPage() {
), ),
labels: { confirm: t`Confirm`, cancel: t`Cancel` }, labels: { confirm: t`Confirm`, cancel: t`Cancel` },
confirmProps: { color: "red" }, confirmProps: { color: "red" },
onConfirm: () => unsubscribe({ id: +id }), onConfirm: () => unsubscribe.execute({ id: +id }),
}) })
} }
@@ -99,13 +97,19 @@ export function FeedDetailsPage() {
if (!feed) return <Loader /> if (!feed) return <Loader />
return ( return (
<Container> <Container>
{errors.length > 0 && ( {modifyFeed.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(modifyFeed.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(modify)}> {unsubscribe.error && (
<Box mb="md">
<Alert messages={errorToStrings(unsubscribe.error)} />
</Box>
)}
<form onSubmit={form.onSubmit(modifyFeed.execute)}>
<Stack> <Stack>
<Title order={3}>{feed.name}</Title> <Title order={3}>{feed.name}</Title>
<Input.Wrapper label={t`Feed URL`}> <Input.Wrapper label={t`Feed URL`}>
@@ -159,7 +163,7 @@ export function FeedDetailsPage() {
<Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}> <Button variant="default" onClick={() => dispatch(redirectToSelectedSource())}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={modifyResult.status === "running"}> <Button type="submit" leftIcon={<TbDeviceFloppy size={16} />} loading={modifyFeed.loading}>
<Trans>Save</Trans> <Trans>Save</Trans>
</Button> </Button>
<Divider orientation="vertical" /> <Divider orientation="vertical" />
@@ -167,7 +171,7 @@ export function FeedDetailsPage() {
color="red" color="red"
leftIcon={<TbTrash size={16} />} leftIcon={<TbTrash size={16} />}
onClick={() => openUnsubscribeModal()} onClick={() => openUnsubscribeModal()}
loading={unsubscribeResult.status === "running"} loading={unsubscribe.loading}
> >
<Trans>Unsubscribe</Trans> <Trans>Unsubscribe</Trans>
</Button> </Button>

View File

@@ -7,8 +7,8 @@ import { useAppDispatch, useAppSelector } from "app/store"
import { LoginRequest } from "app/types" import { LoginRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { Logo } from "components/Logo" import { Logo } from "components/Logo"
import { useAsyncCallback } from "react-async-hook"
import { Link } from "react-router-dom" import { Link } from "react-router-dom"
import useMutation from "use-mutation"
export function LoginPage() { export function LoginPage() {
const serverInfos = useAppSelector(state => state.server.serverInfos) const serverInfos = useAppSelector(state => state.server.serverInfos)
@@ -21,12 +21,11 @@ export function LoginPage() {
}, },
}) })
const [login, loginResult] = useMutation(client.user.login, { const login = useAsyncCallback(client.user.login, {
onSuccess: () => { onSuccess: () => {
dispatch(redirectToRootCategory()) dispatch(redirectToRootCategory())
}, },
}) })
const errors = errorToStrings(loginResult.error)
return ( return (
<Container size="xs"> <Container size="xs">
@@ -40,12 +39,12 @@ export function LoginPage() {
<Title order={2} mb="md"> <Title order={2} mb="md">
<Trans>Log in</Trans> <Trans>Log in</Trans>
</Title> </Title>
{errors.length > 0 && ( {login.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(login.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(login)}> <form onSubmit={form.onSubmit(login.execute)}>
<Stack> <Stack>
<TextInput <TextInput
label={t`User Name or E-mail`} label={t`User Name or E-mail`}
@@ -69,7 +68,7 @@ export function LoginPage() {
</Anchor> </Anchor>
)} )}
<Button type="submit" loading={loginResult.status === "running"}> <Button type="submit" loading={login.loading}>
<Trans>Log in</Trans> <Trans>Log in</Trans>
</Button> </Button>
{serverInfos?.allowRegistrations && ( {serverInfos?.allowRegistrations && (

View File

@@ -6,8 +6,8 @@ import { PasswordResetRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { Logo } from "components/Logo" import { Logo } from "components/Logo"
import { useState } from "react" import { useState } from "react"
import { useAsyncCallback } from "react-async-hook"
import { Link } from "react-router-dom" import { Link } from "react-router-dom"
import useMutation from "use-mutation"
export function PasswordRecoveryPage() { export function PasswordRecoveryPage() {
const [message, setMessage] = useState("") const [message, setMessage] = useState("")
@@ -18,15 +18,11 @@ export function PasswordRecoveryPage() {
}, },
}) })
const [recoverPassword, recoverPasswordResult] = useMutation(client.user.passwordReset, { const recoverPassword = useAsyncCallback(client.user.passwordReset, {
onMutate: () => {
setMessage("")
},
onSuccess: () => { onSuccess: () => {
setMessage(t`An email has been sent if this address was registered. Check your inbox.`) setMessage(t`An email has been sent if this address was registered. Check your inbox.`)
}, },
}) })
const errors = errorToStrings(recoverPasswordResult.error)
return ( return (
<Container size="xs"> <Container size="xs">
@@ -40,17 +36,25 @@ export function PasswordRecoveryPage() {
<Title order={2} mb="md"> <Title order={2} mb="md">
<Trans>Password Recovery</Trans> <Trans>Password Recovery</Trans>
</Title> </Title>
{errors.length > 0 && (
{recoverPassword.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(recoverPassword.error)} />
</Box> </Box>
)} )}
{message && ( {message && (
<Box mb="md"> <Box mb="md">
<Alert level="success" messages={[message]} /> <Alert level="success" messages={[message]} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(recoverPassword)}>
<form
onSubmit={form.onSubmit(req => {
setMessage("")
recoverPassword.execute(req)
})}
>
<Stack> <Stack>
<TextInput <TextInput
type="email" type="email"
@@ -61,7 +65,7 @@ export function PasswordRecoveryPage() {
required required
/> />
<Button type="submit" loading={recoverPasswordResult.status === "running"}> <Button type="submit" loading={recoverPassword.loading}>
<Trans>Recover password</Trans> <Trans>Recover password</Trans>
</Button> </Button>

View File

@@ -7,8 +7,8 @@ import { useAppDispatch, useAppSelector } from "app/store"
import { RegistrationRequest } from "app/types" import { RegistrationRequest } from "app/types"
import { Alert } from "components/Alert" import { Alert } from "components/Alert"
import { Logo } from "components/Logo" import { Logo } from "components/Logo"
import { useAsyncCallback } from "react-async-hook"
import { Link } from "react-router-dom" import { Link } from "react-router-dom"
import useMutation from "use-mutation"
export function RegistrationPage() { export function RegistrationPage() {
const serverInfos = useAppSelector(state => state.server.serverInfos) const serverInfos = useAppSelector(state => state.server.serverInfos)
@@ -22,12 +22,11 @@ export function RegistrationPage() {
}, },
}) })
const [register, registerResult] = useMutation(client.user.register, { const register = useAsyncCallback(client.user.register, {
onSuccess: () => { onSuccess: () => {
dispatch(redirectToRootCategory()) dispatch(redirectToRootCategory())
}, },
}) })
const errors = errorToStrings(registerResult.error)
return ( return (
<Container size="xs"> <Container size="xs">
@@ -48,13 +47,13 @@ export function RegistrationPage() {
)} )}
{serverInfos?.allowRegistrations && ( {serverInfos?.allowRegistrations && (
<> <>
{errors.length > 0 && ( {register.error && (
<Box mb="md"> <Box mb="md">
<Alert messages={errors} /> <Alert messages={errorToStrings(register.error)} />
</Box> </Box>
)} )}
<form onSubmit={form.onSubmit(register)}> <form onSubmit={form.onSubmit(register.execute)}>
<Stack> <Stack>
<TextInput label="User Name" placeholder="User Name" {...form.getInputProps("name")} size="md" required /> <TextInput label="User Name" placeholder="User Name" {...form.getInputProps("name")} size="md" required />
<TextInput <TextInput
@@ -72,7 +71,7 @@ export function RegistrationPage() {
size="md" size="md"
required required
/> />
<Button type="submit" loading={registerResult.status === "running"}> <Button type="submit" loading={register.loading}>
<Trans>Sign up</Trans> <Trans>Sign up</Trans>
</Button> </Button>
<Center> <Center>