Skip to main content

User hooks

These hooks manage user data throughout the application, including user CRUD operations, role assignments, and password verification/changes. Built on SWR for data fetching with automatic caching and revalidation, and useSWRMutation for mutations. Password-related hooks use React state directly rather than SWR.

Hooks

HookDescription
useUsersFetches all users
useUserFetches a single user by ID, with update and delete mutations
useCreateUserCreates a new user
useUserRoleFetches and updates a user's role
useVerifyPasswordVerifies a user's current password
useChangePasswordChanges a user's password

useUsers

Fetches all users from the API.

Signature

function useUsers(): UseUsersReturn

Parameters

None.

Returns

FieldTypeDescription
usersUser[]Array of users, defaults to empty array
isLoadingbooleanSWR loading state
isErrorError | undefinedSWR error state

Example

const { users, isLoading, isError } = useUsers();

if (isLoading) return <Skeleton />;
if (isError) return <ErrorMessage />;

return <UserTable users={users} />;

useUser

Fetches a single user by ID. Also provides updateUser and deleteUser mutations.

Signature

function useUser(userId: string): UseUserReturn

Parameters

ParamTypeRequiredDescription
userIdstringYesThe user's unique identifier

Returns

FieldTypeDescription
userUser | nullThe fetched user, or null if not loaded
isLoadingbooleanSWR loading state
isErrorError | undefinedSWR error state
updateUser(arg: Partial<User>) => Promise<User>Triggers user update mutation
isMutatingbooleanTrue while update is in progress
updateErrorError | undefinedError from update mutation
updatedDataUser | undefinedResponse data from successful update
deleteUser() => Promise<void>Triggers user deletion
isDeletingbooleanTrue while delete is in progress
deleteErrorError | undefinedError from delete mutation

Example

const { user, isLoading, updateUser, deleteUser } = useUser(userId);

const handleSave = async (changes: Partial<User>) => {
await updateUser(changes);
};

const handleDelete = async () => {
await deleteUser();
router.push("/users");
};

Notes

On successful update, revalidates both the individual user cache and the users list. On delete, clears the individual user cache without revalidation and revalidates the users list.


useCreateUser

Creates a new user.

Signature

function useCreateUser(): UseCreateUserReturn

Parameters

None.

Returns

FieldTypeDescription
createUser(arg: { userData: Partial<User> }) => Promise<User>Triggers user creation
isMutatingbooleanTrue while creation is in progress
createErrorError | undefinedError from create mutation
createdDataUser | undefinedThe newly created user

Example

const { createUser, isMutating, createError } = useCreateUser();

const handleSubmit = async (formData: Partial<User>) => {
const newUser = await createUser({ userData: formData });
router.push(`/users/${newUser.id}`);
};

Notes

On success, revalidates the users list cache.


useUserRole

Fetches a user's role and provides a mutation to update it.

Signature

function useUserRole(userId: string): UseUserRoleReturn

Parameters

ParamTypeRequiredDescription
userIdstringYesThe user's unique identifier

Returns

FieldTypeDescription
userRoleRole | nullThe user's current role, or null if not loaded
isLoadingbooleanSWR loading state
isErrorError | undefinedSWR error state
updateUserRole(arg: { roleId: number }) => Promise<Role>Triggers role update
isMutatingbooleanTrue while update is in progress
updatedDataRole | undefinedResponse data from successful update
updateErrorError | undefinedError from update mutation

Example

const { userRole, updateUserRole, isMutating } = useUserRole(userId);

const handleRoleChange = async (roleId: number) => {
await updateUserRole({ roleId });
};

Notes

On success, revalidates the user role cache, individual user cache, and users list.


useVerifyPassword

Verifies a user's current password. Uses React state instead of SWR.

Signature

function useVerifyPassword(userId: string): UseVerifyPasswordReturn

Parameters

ParamTypeRequiredDescription
userIdstringYesThe user's unique identifier

Returns

FieldTypeDescription
verifyPassword(password: string) => Promise<boolean>Verifies the password, returns true if valid
isLoadingbooleanTrue while verification is in progress
errorError | nullError from verification attempt
isValidboolean | nullResult of last verification, null if not yet verified

Example

const { verifyPassword, isLoading, isValid } = useVerifyPassword(userId);

const handleVerify = async () => {
const valid = await verifyPassword(currentPassword);
if (valid) {
setStep("newPassword");
}
};

useChangePassword

Changes a user's password. Uses React state instead of SWR.

Signature

function useChangePassword(userId: string): UseChangePasswordReturn

Parameters

ParamTypeRequiredDescription
userIdstringYesThe user's unique identifier

Returns

FieldTypeDescription
changePassword(oldPassword: string, newPassword: string) => Promise<void>Changes the user's password
isLoadingbooleanTrue while change is in progress
errorError | nullError from change attempt
successbooleanTrue if password was changed successfully

Example

const { changePassword, isLoading, error, success } = useChangePassword(userId);

const handleSubmit = async () => {
await changePassword(oldPassword, newPassword);
};

if (success) {
return <SuccessMessage>Password updated</SuccessMessage>;
}