Use server actions instead of client-side API calls

This commit is contained in:
Darren Clarke 2024-08-05 23:31:15 +02:00
parent 5a3127dcb0
commit aa453954ed
30 changed files with 703 additions and 462 deletions

View file

@ -1,11 +1,19 @@
"use client";
import { FC } from "react";
import { FC, useState, useEffect } from "react";
import { useFormState } from "react-dom";
import { useRouter } from "next/navigation";
import { Grid } from "@mui/material";
import { Dialog, Button, TextField, Autocomplete } from "@link-stack/ui";
import {
Dialog,
Button,
TextField,
Autocomplete,
Select,
} from "@link-stack/ui";
import { createTicketAction } from "app/_actions/tickets";
import useSWR from "swr";
import { getCustomersAction } from "app/_actions/users";
import { getGroupsAction } from "app/_actions/groups";
interface TicketCreateDialogProps {
open: boolean;
@ -16,6 +24,8 @@ export const TicketCreateDialog: FC<TicketCreateDialogProps> = ({
open,
closeDialog,
}) => {
const [customers, setCustomers] = useState([]);
const [groups, setGroups] = useState([]);
const initialState = {
messages: [],
errors: [],
@ -38,16 +48,41 @@ export const TicketCreateDialog: FC<TicketCreateDialogProps> = ({
createTicketAction,
initialState,
);
const { data: users, error: usersError }: any = useSWR({
url: "/api/v1/users",
method: "GET",
});
const customers =
users?.filter((user: any) => user.role_ids.includes(3)) ?? [];
const formattedCustomers = customers.map((customer: any) => ({
label: customer.login,
id: `${customer.id}`,
}));
const [liveFormState, setLiveFormState] = useState(formState);
const updateFormState = (field: string, value: any) => {
console.log({ value });
const newState = { ...liveFormState };
newState.values[field] = value;
setLiveFormState(newState);
};
useEffect(() => {
const fetchUsers = async () => {
const result = await getCustomersAction();
console.log({ result });
setCustomers(result);
};
fetchUsers();
}, []);
useEffect(() => {
const fetchGroups = async () => {
const result = await getGroupsAction();
console.log({ result });
setGroups(result);
};
fetchGroups();
}, []);
const router = useRouter();
useEffect(() => {
if (formState.success) {
closeDialog();
}
}, [formState.success, router]);
return (
<Dialog
@ -74,11 +109,21 @@ export const TicketCreateDialog: FC<TicketCreateDialogProps> = ({
>
<Grid container direction="column" spacing={3}>
<Grid item>
<Autocomplete
<Select
name="groupId"
label="Group"
getOptions={() => groups as any}
formState={liveFormState}
updateFormState={updateFormState}
/>
</Grid>
<Grid item>
<Select
name="customerId"
label="Customer"
options={formattedCustomers}
formState={formState}
getOptions={() => customers as any}
formState={liveFormState}
updateFormState={updateFormState}
/>
</Grid>
<Grid item>