Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

43 Add user #56

Merged
merged 13 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const App = (): JSX.Element => (
<ToastProvider>
<AppRouter />
<Toasts />
<ReactQueryDevtools initialIsOpen={false} />
<ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-left" />
</ToastProvider>
</AxiosProvider>
</AuthProvider>
Expand Down
36 changes: 0 additions & 36 deletions src/common/components/Card/CardRow.scss

This file was deleted.

33 changes: 24 additions & 9 deletions src/common/components/Card/CardRow.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { IonRow } from '@ionic/react';
import { PropsWithChildren } from 'react';
import { IonCol, IonGrid, IonRow } from '@ionic/react';
import { ComponentPropsWithoutRef } from 'react';
import classNames from 'classnames';

import './CardRow.scss';
import { BaseComponentProps } from '../types';

/**
* Properties for the `CardRow` component.
* @see {@link BaseComponentProps}
* @see {@link PropsWithChildren}
* @see {@link IonCol}
*/
interface CardRowProps extends BaseComponentProps, PropsWithChildren {}
interface CardRowProps extends BaseComponentProps, ComponentPropsWithoutRef<typeof IonCol> {}

/**
* The `CardRow` component displays an `IonCard` (or other Card component)
Expand All @@ -21,11 +20,27 @@ interface CardRowProps extends BaseComponentProps, PropsWithChildren {}
* @param {CardRowProps} props - Component properties.
* @returns JSX
*/
const CardRow = ({ children, className, testid = 'row-card' }: CardRowProps): JSX.Element => {
const CardRow = ({
className,
testid = 'row-card',
sizeMd = '8',
offsetMd = '2',
sizeLg = '6',
offsetLg = '3',
...colProps
}: CardRowProps): JSX.Element => {
return (
<IonRow className={classNames('row-card', className)} data-testid={testid}>
<div className="wrapper">{children}</div>
</IonRow>
<IonGrid className={classNames('row-card', className)} data-testid={testid}>
<IonRow>
<IonCol
sizeMd={sizeMd}
offsetMd={offsetMd}
sizeLg={sizeLg}
offsetLg={offsetLg}
{...colProps}
/>
</IonRow>
</IonGrid>
);
};

Expand Down
3 changes: 3 additions & 0 deletions src/common/components/Icon/Icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
faMapLocationDot,
faPenToSquare,
faPhone,
faPlus,
faSignOutAlt,
faTrash,
faTriangleExclamation,
Expand Down Expand Up @@ -46,6 +47,7 @@ export enum IconName {
MapLocationDot = 'map_location_dot',
PenToSquare = 'pen_to_square',
Phone = 'phone',
Plus = 'plus',
SignOut = 'sign_out',
Trash = 'trash',
TriangleExclamation = 'triangle_exclamation',
Expand All @@ -66,6 +68,7 @@ const icons: Record<IconName, IconProp> = {
map_location_dot: faMapLocationDot,
pen_to_square: faPenToSquare,
phone: faPhone,
plus: faPlus,
sign_out: faSignOutAlt,
trash: faTrash,
triangle_exclamation: faTriangleExclamation,
Expand Down
4 changes: 4 additions & 0 deletions src/common/components/Router/TabNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import HomePage from 'pages/Home/HomePage';
import UserDetailPage from 'pages/Users/components/UserDetail/UserDetailPage';
import UserListPage from 'pages/Users/components/UserList/UserListPage';
import UserEditPage from 'pages/Users/components/UserEdit/UserEditPage';
import UserAddPage from 'pages/Users/components/UserAdd/UserAddPage';
import AccountPage from 'pages/Account/AccountPage';

/**
Expand Down Expand Up @@ -45,6 +46,9 @@ const TabNavigation = (): JSX.Element => {
<Route exact path="/tabs/users/:userId/edit">
<UserEditPage />
</Route>
<Route exact path="/tabs/users/add">
<UserAddPage />
</Route>
<Route exact path="/tabs/account">
<AccountPage />
</Route>
Expand Down
10 changes: 0 additions & 10 deletions src/pages/Auth/SignIn/components/SignInForm.scss
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,6 @@
ion-button.button-submit {
margin-top: 2rem;
}

.row-message {
margin: 1rem 0;

&.row-card {
.wrapper {
width: 100% !important;
}
}
}
}

.form-signin-popover {
Expand Down
9 changes: 5 additions & 4 deletions src/pages/Auth/SignIn/components/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { BaseComponentProps } from 'common/components/types';
import { useSignIn } from '../api/useSignIn';
import { useProgress } from 'common/hooks/useProgress';
import Input from 'common/components/Input/Input';
import CardRow from 'common/components/Card/CardRow';
import ErrorCard from 'common/components/Card/ErrorCard';
import Icon, { IconName } from 'common/components/Icon/Icon';
import HeaderRow from 'common/components/Text/HeaderRow';
Expand Down Expand Up @@ -51,9 +50,11 @@ const SignInForm = ({ className, testid = 'form-signin' }: SignInFormProps): JSX
return (
<div className={classNames('form-signin', className)} data-testid={testid}>
{error && (
<CardRow className="row-message" testid={`${testid}-error`}>
<ErrorCard content={`We were unable verify your credentials. Please try again.`} />
</CardRow>
<ErrorCard
content={`We were unable verify your credentials. Please try again. ${error}`}
className="ion-margin-bottom"
testid={`${testid}-error`}
/>
)}

<Formik<SignInFormValues>
Expand Down
63 changes: 63 additions & 0 deletions src/pages/Users/api/useCreateUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { useAxios } from 'common/hooks/useAxios';
import { useConfig } from 'common/hooks/useConfig';
import { User } from 'common/models/user';
import { QueryKey } from 'common/utils/constants';

/**
* Describes the properties of a `User` needed to create a new `User`.
*/
export type CreateUserDTO = Pick<User, 'email' | 'name' | 'phone' | 'username' | 'website'>;

/**
* The `useCreateUser` mutation function variables.
* @param {CreateUserDTO} user - The user to be created.
*/
export type CreateUserVariables = {
user: CreateUserDTO;
};

/**
* An API hook which updates a single `User`. Returns a `UseMutationResult`
* object whose `mutate` attribute is a function to create a `User`.
*
* When succesful, the hook updates the cached `User` query data.
* @returns Returns a `UseMutationResult`.
*/
export const useCreateUser = () => {
const axios = useAxios();
const queryClient = useQueryClient();
const config = useConfig();

/**
* Create a `User`.
* @param {CreateUserVariables} variables - The mutation function variables.
* @returns {Promise<User>} Returns a Promise which resolves to the created
* `User`.
*/
const createUser = async ({ user }: CreateUserVariables): Promise<User> => {
const response = await axios.request({
method: 'post',
url: `${config.VITE_BASE_URL_API}/users`,
data: user,
});

return response.data;
};

return useMutation({
mutationFn: createUser,
onSuccess: (data) => {
// update cached query data
const userId: string = '' + data.id;
queryClient.setQueryData<User[]>([QueryKey.Users], (cachedUsers) =>
cachedUsers ? [...cachedUsers, data] : [data],
);
queryClient.setQueryData<User>([QueryKey.Users, userId], data);
// you may [also|instead] choose to invalidate certaincached queries, triggering refetch
// queryClient.invalidateQueries({ queryKey: [QueryKey.Users], exact: true });
// queryClient.invalidateQueries({ queryKey: [QueryKey.Users, userId] });
},
});
};
4 changes: 2 additions & 2 deletions src/pages/Users/api/useUpdateUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import { User } from 'common/models/user';
import { QueryKey } from 'common/utils/constants';

/**
* The`useUpdateUser` mutation function variables.
* The `useUpdateUser` mutation function variables.
* @param {User} user - The updated `User` object.
*/
export type UpdateUserVariables = {
user: User;
};

/**
* An API hook which updates a single `user`. Returns a `UseMutationResult`
* An API hook which updates a single `User`. Returns a `UseMutationResult`
* object whose `mutate` attribute is a function to udate a `User`.
*
* When successful, the hook updates the cached `User` query data.
Expand Down
77 changes: 77 additions & 0 deletions src/pages/Users/components/UserAdd/UserAdd.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { IonCol, IonGrid, IonRow, useIonRouter } from '@ionic/react';
import { useState } from 'react';
import classNames from 'classnames';

import { BaseComponentProps } from 'common/components/types';
import { useCreateUser } from 'pages/Users/api/useCreateUser';
import { useProgress } from 'common/hooks/useProgress';
import { useToasts } from 'common/hooks/useToasts';
import { DismissButton } from 'common/components/Toast/Toast';
import ErrorCard from 'common/components/Card/ErrorCard';
import UserForm from '../UserForm/UserForm';

/**
* The `UserAdd` component renders a Formik form for creating a `User`.
* @param {BaseComponentProps} props - Component properties.
* @returns {JSX.Element} JSX
*/
const UserAdd = ({ className, testid = 'user-add' }: BaseComponentProps): JSX.Element => {
const [error, setError] = useState<string>('');
const router = useIonRouter();
const { mutate: createUser } = useCreateUser();
const { setProgress } = useProgress();
const { createToast } = useToasts();

const onCancel = () => {
router.goBack();
};

return (
<div className={classNames('user-add', className)} data-testid={testid}>
<IonGrid>
<IonRow>
<IonCol size="12" sizeMd="10" sizeLg="8" sizeXl="6">
{error && (
<ErrorCard
content={`We are experiencing problems processing your request. ${error}`}
className="ion-margin-bottom"
testid={`${testid}-error`}
/>
)}

<UserForm
onCancel={onCancel}
onSubmit={(values, { setSubmitting }) => {
setProgress(true);
setError('');
createUser(
{ user: values },
{
onSuccess: (user) => {
setProgress(false);
setSubmitting(false);
createToast({
buttons: [DismissButton],
duration: 5000,
message: `${user.name} created`,
});
router.push(`/tabs/users/${user.id}`, 'forward', 'replace');
},
onError(error) {
setProgress(false);
setError(error.message);
setSubmitting(false);
},
},
);
}}
testid={`${testid}-form`}
/>
</IonCol>
</IonRow>
</IonGrid>
</div>
);
};

export default UserAdd;
5 changes: 5 additions & 0 deletions src/pages/Users/components/UserAdd/UserAddFab.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.fab-user-add {
.icon {
font-size: 1.125rem;
}
}
35 changes: 35 additions & 0 deletions src/pages/Users/components/UserAdd/UserAddFab.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { IonFab, IonFabButton } from '@ionic/react';
import classNames from 'classnames';

import './UserAddFab.scss';
import { BaseComponentProps } from 'common/components/types';
import Icon, { IconName } from 'common/components/Icon/Icon';

/**
* Properties for the `UserAddFab` component.
*/
interface UserAddFabProps extends BaseComponentProps {}

/**
* The `UserAddFab` renders an Ionic Floating Action Button, or FAB.
* The button navigates to the create new `User` form when clicked.
* @param {UserAddFabProps} props - Component properties.
* @returns {JSX.Element} JSX
*/
const UserAddFab = ({ className, testid = 'fab-user-add' }: UserAddFabProps): JSX.Element => {
return (
<IonFab
className={classNames('fab-user-add', className)}
data-testid={testid}
slot="fixed"
vertical="bottom"
horizontal="end"
>
<IonFabButton routerLink="/tabs/users/add">
<Icon icon={IconName.Plus} />
</IonFabButton>
</IonFab>
);
};

export default UserAddFab;
Loading