refactor (admin/)users store
This commit is contained in:
@@ -1,8 +1,8 @@
|
|||||||
import toast from "react-hot-toast";
|
|
||||||
import Modal from "../Modal";
|
import Modal from "../Modal";
|
||||||
import useUserStore from "@/store/admin/users";
|
|
||||||
import Button from "../ui/Button";
|
import Button from "../ui/Button";
|
||||||
import { useTranslation } from "next-i18next";
|
import { useTranslation } from "next-i18next";
|
||||||
|
import { useDeleteUser } from "@/hooks/store/admin/users";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
onClose: Function;
|
onClose: Function;
|
||||||
@@ -11,22 +11,22 @@ type Props = {
|
|||||||
|
|
||||||
export default function DeleteUserModal({ onClose, userId }: Props) {
|
export default function DeleteUserModal({ onClose, userId }: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { removeUser } = useUserStore();
|
|
||||||
|
|
||||||
const deleteUser = async () => {
|
const [submitLoader, setSubmitLoader] = useState(false);
|
||||||
const load = toast.loading(t("deleting_user"));
|
const deleteUser = useDeleteUser();
|
||||||
|
|
||||||
const response = await removeUser(userId);
|
const submit = async () => {
|
||||||
|
if (!submitLoader) {
|
||||||
|
setSubmitLoader(true);
|
||||||
|
|
||||||
toast.dismiss(load);
|
await deleteUser.mutateAsync(userId, {
|
||||||
|
onSuccess: () => {
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (response.ok) {
|
setSubmitLoader(false);
|
||||||
toast.success(t("user_deleted"));
|
|
||||||
} else {
|
|
||||||
toast.error(response.data as string);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onClose();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -45,7 +45,7 @@ export default function DeleteUserModal({ onClose, userId }: Props) {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button className="ml-auto" intent="destructive" onClick={deleteUser}>
|
<Button className="ml-auto" intent="destructive" onClick={submit}>
|
||||||
<i className="bi-trash text-xl" />
|
<i className="bi-trash text-xl" />
|
||||||
{t("delete_confirmation")}
|
{t("delete_confirmation")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import toast from "react-hot-toast";
|
import toast from "react-hot-toast";
|
||||||
import Modal from "../Modal";
|
import Modal from "../Modal";
|
||||||
import useUserStore from "@/store/admin/users";
|
|
||||||
import TextInput from "../TextInput";
|
import TextInput from "../TextInput";
|
||||||
import { FormEvent, useState } from "react";
|
import { FormEvent, useState } from "react";
|
||||||
import { useTranslation, Trans } from "next-i18next";
|
import { useTranslation, Trans } from "next-i18next";
|
||||||
|
import { useAddUser } from "@/hooks/store/admin/users";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
onClose: Function;
|
onClose: Function;
|
||||||
@@ -20,7 +20,9 @@ const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
|
|||||||
|
|
||||||
export default function NewUserModal({ onClose }: Props) {
|
export default function NewUserModal({ onClose }: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { addUser } = useUserStore();
|
|
||||||
|
const addUser = useAddUser();
|
||||||
|
|
||||||
const [form, setForm] = useState<FormData>({
|
const [form, setForm] = useState<FormData>({
|
||||||
name: "",
|
name: "",
|
||||||
username: "",
|
username: "",
|
||||||
@@ -44,24 +46,15 @@ export default function NewUserModal({ onClose }: Props) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (checkFields()) {
|
if (checkFields()) {
|
||||||
if (form.password.length < 8)
|
|
||||||
return toast.error(t("password_length_error"));
|
|
||||||
|
|
||||||
setSubmitLoader(true);
|
setSubmitLoader(true);
|
||||||
|
|
||||||
const load = toast.loading(t("creating_account"));
|
await addUser.mutateAsync(form, {
|
||||||
|
onSuccess: () => {
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const response = await addUser(form);
|
|
||||||
|
|
||||||
toast.dismiss(load);
|
|
||||||
setSubmitLoader(false);
|
setSubmitLoader(false);
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
toast.success(t("user_created"));
|
|
||||||
onClose();
|
|
||||||
} else {
|
|
||||||
toast.error(response.data as string);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
toast.error(t("fill_all_fields_error"));
|
toast.error(t("fill_all_fields_error"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import toast from "react-hot-toast";
|
||||||
|
import { useTranslation } from "next-i18next";
|
||||||
|
|
||||||
|
const useUsers = () => {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["users"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await fetch("/api/v1/users");
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 401) {
|
||||||
|
window.location.href = "/dashboard";
|
||||||
|
}
|
||||||
|
throw new Error("Failed to fetch users.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return data.response;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const useAddUser = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (body: any) => {
|
||||||
|
if (body.password.length < 8) throw new Error(t("password_length_error"));
|
||||||
|
|
||||||
|
const load = toast.loading(t("creating_account"));
|
||||||
|
|
||||||
|
const response = await fetch("/api/v1/users", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.response);
|
||||||
|
|
||||||
|
toast.dismiss(load);
|
||||||
|
|
||||||
|
return data.response;
|
||||||
|
},
|
||||||
|
onSuccess: (data) => {
|
||||||
|
queryClient.setQueryData(["users"], (oldData: any) => [...oldData, data]);
|
||||||
|
toast.success(t("user_created"));
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast.error(error.message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const useDeleteUser = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (userId: number) => {
|
||||||
|
const load = toast.loading(t("deleting_user"));
|
||||||
|
|
||||||
|
const response = await fetch(`/api/v1/users/${userId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.response);
|
||||||
|
|
||||||
|
toast.dismiss(load);
|
||||||
|
|
||||||
|
return data.response;
|
||||||
|
},
|
||||||
|
onSuccess: (data, variables) => {
|
||||||
|
queryClient.setQueryData(["users"], (oldData: any) =>
|
||||||
|
oldData.filter((user: any) => user.id !== variables)
|
||||||
|
);
|
||||||
|
toast.success(t("user_deleted"));
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast.error(error.message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export { useUsers, useAddUser, useDeleteUser };
|
||||||
+4
-8
@@ -1,11 +1,11 @@
|
|||||||
import NewUserModal from "@/components/ModalContent/NewUserModal";
|
import NewUserModal from "@/components/ModalContent/NewUserModal";
|
||||||
import useUserStore from "@/store/admin/users";
|
|
||||||
import { User as U } from "@prisma/client";
|
import { User as U } from "@prisma/client";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslation } from "next-i18next";
|
import { useTranslation } from "next-i18next";
|
||||||
import getServerSideProps from "@/lib/client/getServerSideProps";
|
import getServerSideProps from "@/lib/client/getServerSideProps";
|
||||||
import UserListing from "@/components/UserListing";
|
import UserListing from "@/components/UserListing";
|
||||||
|
import { useUsers } from "@/hooks/store/admin/users";
|
||||||
|
|
||||||
interface User extends U {
|
interface User extends U {
|
||||||
subscriptions: {
|
subscriptions: {
|
||||||
@@ -21,7 +21,7 @@ type UserModal = {
|
|||||||
export default function Admin() {
|
export default function Admin() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const { users, setUsers } = useUserStore();
|
const { data: users = [] } = useUsers();
|
||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const [filteredUsers, setFilteredUsers] = useState<User[]>();
|
const [filteredUsers, setFilteredUsers] = useState<User[]>();
|
||||||
@@ -33,10 +33,6 @@ export default function Admin() {
|
|||||||
|
|
||||||
const [newUserModal, setNewUserModal] = useState(false);
|
const [newUserModal, setNewUserModal] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setUsers();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-6xl mx-auto p-5">
|
<div className="max-w-6xl mx-auto p-5">
|
||||||
<div className="flex sm:flex-row flex-col justify-between gap-2">
|
<div className="flex sm:flex-row flex-col justify-between gap-2">
|
||||||
@@ -71,7 +67,7 @@ export default function Admin() {
|
|||||||
|
|
||||||
if (users) {
|
if (users) {
|
||||||
setFilteredUsers(
|
setFilteredUsers(
|
||||||
users.filter((user) =>
|
users.filter((user: any) =>
|
||||||
JSON.stringify(user)
|
JSON.stringify(user)
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.includes(e.target.value.toLowerCase())
|
.includes(e.target.value.toLowerCase())
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
import { User as U } from "@prisma/client";
|
|
||||||
import { create } from "zustand";
|
|
||||||
|
|
||||||
interface User extends U {
|
|
||||||
subscriptions: {
|
|
||||||
active: boolean;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResponseObject = {
|
|
||||||
ok: boolean;
|
|
||||||
data: object | string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UserStore = {
|
|
||||||
users: User[];
|
|
||||||
setUsers: () => void;
|
|
||||||
addUser: (body: Partial<U>) => Promise<ResponseObject>;
|
|
||||||
removeUser: (userId: number) => Promise<ResponseObject>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const useUserStore = create<UserStore>((set) => ({
|
|
||||||
users: [],
|
|
||||||
setUsers: async () => {
|
|
||||||
const response = await fetch("/api/v1/users");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok) set({ users: data.response });
|
|
||||||
else if (response.status === 401) window.location.href = "/dashboard";
|
|
||||||
},
|
|
||||||
addUser: async (body) => {
|
|
||||||
const response = await fetch("/api/v1/users", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok)
|
|
||||||
set((state) => ({
|
|
||||||
users: [...state.users, data.response],
|
|
||||||
}));
|
|
||||||
|
|
||||||
return { ok: response.ok, data: data.response };
|
|
||||||
},
|
|
||||||
removeUser: async (userId) => {
|
|
||||||
const response = await fetch(`/api/v1/users/${userId}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok)
|
|
||||||
set((state) => ({
|
|
||||||
users: state.users.filter((user) => user.id !== userId),
|
|
||||||
}));
|
|
||||||
|
|
||||||
return { ok: response.ok, data: data.response };
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
export default useUserStore;
|
|
||||||
Reference in New Issue
Block a user