Tips for deleting a user from the UI prior to making changes to the database

Is there a way to remove a participant from the client side before updating the actual state when the submit button is clicked?

Currently, I am working with react-hook-form and TanstackQuery. My process involves fetching data using Tanstack query, displaying it with defaultValues in my form fields, but I'm facing an issue where I need to delete a user on the client side first.

Edit/[id]/page/tsx.

const EditAppointment =({params}) => {

  const appoinment = useQuery({
    queryKey: ['appointment', 'data', 'history', id],
    queryFn: () => fetch(`/api/single-sched/${id}`).then((res) => res.json())
  })


  const { data } = appoinment

  const form = useForm<CreateAppointmentSchemaType>({
    resolver: zodResolver(CreateAppointmentSchema),
  });

  const removeAssistant = (name: string) => (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    console.log(`Removing assistant: ${name}`);
  }

return (
   <Form {...form}>
     <form>
       <FormField
            control={form.control}
            name="title"
            defaultValue={data?.title}
            render={({ field }) => (
                <FormItem>
                  <FormLabel>Title</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                    </FormItem>
                  )}
           />


<Table className='max-w-[400px]'>
      <TableHeader>
           <TableRow>
              <TableHead>Name</TableHead>
               <TableHead>Email</TableHead>
               <TableHead></TableHead>
           </TableRow>
              </TableHeader>
                 <TableBody>
                   {data?.name_of_assistance.map((item:{name: string, email: string}) => {
                          return (
                            <TableRow>
                          <TableCell>{item.name}</TableCell>
                          <TableCell>{item.email}</TableCell>
                          <TableCell> 
                            <Button onClick={() => removeAssistant(item.name)}  
           variant="destructive" size="icon">
                              <Trash2 /> 
                            </Button>
                             </TableCell>
                        </TableRow>
                          )
                        })} 
                      </TableBody>
                    </Table>

     </form>
   <Form />
)
}


Answer №1

To manage the local state for the list of participants, you can utilize the useState hook in order to handle updates when the remove button is clicked on the form. Then, once the form is submitted, the actual update can be sent to the backend.

I've made modifications to your code to incorporate the local state functionality:

const EditAppointment = ({ params }) => {
  const { id } = params;
  
  const appointment = useQuery({
    queryKey: ['appointment', 'data', 'history', id],
    queryFn: () => fetch(`/api/single-sched/${id}`).then((res) => res.json()),
  });

  const { data } = appointment;

  const [assistants, setAssistants] = useState([]);
 const [error, setError] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (data?.name_of_assistance) {
      setAssistants(data.name_of_assistance);
    }
  }, [data]);

  const form = useForm<CreateAppointmentSchemaType>({
    resolver: zodResolver(CreateAppointmentSchema),
    defaultValues: data,
  });

  const removeAssistant = (name: string) => {
    setAssistants((prev) => prev.filter((assistant) => assistant.name !== name));
  };

 const onSubmit = async (formData) => {
    setIsSubmitting(true);
    setError(null);

    try {
      // Add to formData
      formData.name_of_assistance = assistants;

      // Submit  to backend
      const response = await fetch(`/api/update-sched/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('Failed --');
      }

      // happy flow
      console.log('updated successfully');
    } catch (error) {
      // error handling
      console.error(error);
      setError('An error occurred. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };


  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Title</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
            </FormItem>
          )}
        />

        <Table className='max-w-[400px]'>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Email</TableHead>
              <TableHead></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {assistants.map((item) => (
              <TableRow key={item.name}>
                <TableCell>{item.name}</TableCell>
                <TableCell>{item.email}</TableCell>
                <TableCell>
                  <Button
                    onClick={(e) => {
                      e.preventDefault();
                      removeAssistant(item.name);
                    }}
                    variant="destructive"
                    size="icon"
                  >
                    <Trash2 />
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        <Button type="submit">Submit</Button>
      </form>
    </Form>
  );
};

An onSubmit function has been introduced to handle the submission of the updated data to the backend upon clicking submit. Additionally, there is a try-catch block included for error handling in case the API call fails.

Trust this makes things clearer!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Is it possible to integrate React Bootstrap with Next.js?

Is it possible to integrate react-bootstrap with Next.js? I have the latest versions of both, but none of my react-bootstrap components are showing up in my app. I've searched online for solutions, but haven't found anything helpful. If needed, I ...

Implementing strict validation for Angular @Input by allowing only predefined values

I am facing an issue where I receive a string value as a parameter in a component, but I want to restrict the possible values that can be passed as a parameter, similar to using an enum. Currently, I have: @Input() type: string = ''; However, ...

Redeeming tokens from different origins is only allowed for clients classified as the 'Single-Page Application' type

I've encountered an issue while trying to obtain an access token from the MS Graph API within a Next.js application. Everything works perfectly in Postman, but when attempting it in my app, I receive the error message: "AADSTS9002326: Cross-origin tok ...

Is there a TypeScript alternative to triggering a click event on a specific class using $(".class").click()?

I am currently utilizing a date range picker within an Angular project. <button type="button" class="btn btn-danger daterange-ranges"> <i class="icon-calendar22 position-left"></i> <span></span> <b class="caret"></b ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

Utilizing HttpClient in a static method service with Angular

One of my services contains a static method that I use for some initialization treatment. Within this method, I need to retrieve data from a web service @Injectable() export class FeaturesInitializationService { static allowedFeaturesModul ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

Using Next.js, meta og tags fail to function properly, even when using the Facebook debugger tool

Currently, I am utilizing React and NextJS (latest versions) without incorporating Redux. I am looking to dynamically alter the content of meta tags on my website. Although the meta tags are successfully created when I render the page and inspect with Ch ...

Guide on updating the URL for the login page in the Next-Auth configuration

I successfully integrated authentication using Next-Auth in my Next.js project. In the index.js file (as per the Next-Auth documentation), I only return a User if there is an active session export default function Home({characters}) { const {data: ses ...

Setting up shortcuts for webpack using lerna and typescript

I have set up a repository to showcase an issue I am facing: https://github.com/vileen/lerna-webpack-typescript-aliases-issue (the app does not start properly, but that's not the main concern). The main question here is how can I enhance importing fr ...

Is there a way to incorporate new members into a pre-existing type in TypeScript?

While examining the definition file for the commander project, one can observe the following interface being utilized: interface IExportedCommand extends ICommand { Command: commander.ICommandStatic; Option: commander.IOptionStatic; [key: stri ...

Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components Parent Component: deposit.component.html <div> <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit> </div> Deposit Component ...

Disabling react-query remains unattainable as long as the variable holds a truth

Experimenting with react-query in a NextJS project, I am encountering an issue where I seem unable to control its execution partially. Although no request is being made, it still appears as an entry in the react-query dev tools: const { data, status } = us ...

Generating an HTML version of a specific nextJS page by clicking a button that includes constantly changing data

I have a current project where I am tasked with filling a template.tsx file with the information gathered from a form, and then using that data to create an HTML file which can be downloaded to the user's device. Does anyone know how I can accomplish ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

What is the process for importing API routes in NextJS to utilize getStaticProps functionality?

Utilizing NextJS's getStaticProps to retrieve data from an external API has been a key part of my project. While diving into the data fetching guidelines provided on the getStaticProps documentation page, I stumbled upon this specific advisory: Note ...

What is the best way to utilize the fresh Sanitizer API in Typescript?

Everything seems to be working well on Codepen, even without using window. It's surprising because I'm used to having to use window.x if ( 'Sanitizer' in window ) { console.log( 'sani', 'Sanitizer' in window ); } ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...