Error TS2322: The function expecting a type of 'FormEventHandler<HTMLFormElement>' cannot be assigned the type '(data: TicketFullDTO) => Promise<void>'

I am currently working on creating an edit form to modify data from a database based on its ID. Here is my approach:

    import React, {FormEvent, useEffect, useState} from "react";
    import TextField from "@material-ui/core/TextField";
    import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
    import {
      TicketFullDTO,
      TicketStatusTypesDTO,
    } from "../../service/support/types";
    import {
      getTicket,
      getTicketStatusTypes,
      updateTicket,
    } from "../../service/support";
    import { useHistory, useParams } from "react-router-dom";
    import InputLabel from "@mui/material/InputLabel";
    import Select from "@mui/material/Select";
    import MenuItem from "@mui/material/MenuItem";
    import { FormControl } from "@mui/material";
    import { Moment } from "moment";
    import { RouteParams } from "../../service/utils";
       
    export default function TicketProfile(props: any) {
      const classes = useStyles();
      let history = useHistory();
      let requestParams = useParams<RouteParams>();

      const [status, setStatus] = useState<string>("");
      const [submitDate, setSubmitDate] = useState<Moment | null>(null);
    
      // This function will only run if all input validations are met.
      const onSubmit = async (formData: TicketFullDTO) => {
        console.log(formData);

        updateTicket(requestParams.id, formData)
          .then(({ response }) => {
            console.log(response.title);
            history.replace("/support");
          })
          .catch((error) => {
            console.log(error);
          });
      };
    
      const [ticketCategoriesList, setTicketCategoriesList] = useState<
        TicketCategoryTypesDTO[]
      >([]);
      const [ticket, setTicket] = useState<TicketFullDTO>();
    
      useEffect(() => {
        fetchSingleTicket();
      }, []);
    
      const fetchSingleTicket = async () => {
        getTicket(requestParams.id)
          .then(({ data }) => {
            setTicket(data);
          })
          .catch((err) => {
            console.error(err);
          });
      };
    
      const [ticketStatusList, setTicketStatusList] = useState<
        TicketStatusTypesDTO[]
      >([]);
    
      useEffect(() => {
        retrieveTicketStatusData();
      }, []);
    
      const retrieveTicketStatusData = async () => {
        getTicketStatusTypes()
          .then((response) => {
            setTicketStatusList(response.data);
          })
          .catch((err) => {
            console.error(err);
          });
      };
    
      return (
        <Container>
            <form onSubmit={onSubmit}>

                          .........

                          <TextField
                            value={ticket?.title}
                            id="title"                                             
                            onChange={({ target: { value } }) => {
                              setTicket({ ...ticket, title: value });
                            }}
                          />

                          .........

                          <FormControl>
                            <TextField
                              label="Submit Date"
                              id="submit-date"
                              type="date"
                              defaultValue={ticket?.submitDate}                             
                              //@ts-ignore
                              onInput={(event) => setSubmitDate(event.target.value)}
                            />
                          </FormControl>
                       
                          ..........

                            <Select
                              labelId="status-label"
                              id="status-helper"
                              value={ticket?.status}
                              onChange={(event) => setStatus(event.target.value)}
                              required
                            >
                              {ticketStatusList.map((item) => (
                                <MenuItem value={item.code}>
                                  {item.name}
                                </MenuItem>
                              ))}
                            </Select>
                          </FormControl>

                         ...........
                      
                          <Button
                            type="submit"
                          >
                            Update Ticket
                          </Button>                       
    
        </Container>
      );
    }


.....


export async function updateTicket(
    id: string,
    data: TicketFullDTO
): Promise<AxiosResponse<TicketFullDTO>> {
  return await axios.post<TicketFullDTO>(
      `${baseUrl}/management/support/tickets/ticket/${id}`,
      {
        data,
      }
  );
}

export interface TicketFullDTO {
    id?: number,
    title?: string,
    status?: string,
    submitDate?: Moment | null
}

When I reach this line: <form onSubmit={onSubmit}>, I encounter the following error:

TS2322: Type '(data: TicketFullDTO) => Promise<void>' is not assignable to type 'FormEventHandler<HTMLFormElement>'.   Types of parameters 'data' and 'event' are incompatible.     Type 'FormEvent<HTMLFormElement>' has no properties in common with type 'TicketFullDTO'.  index.d.ts(1390, 9): The expected type comes from property 'onSubmit' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>'

Do you have any suggestions on how to resolve this issue?

Answer №1

It seems like the best approach is to utilize the ticket state variable as your main source of data since all fields are updating that specific state. You can achieve this by:

const handleSubmit = async () => {
  updateTicket(requestParams.id, ticket)
    .then(({ data }) => {
      console.log(data.title);
      history.replace("/support");
    })
    .catch((err) => {
      console.log(err);
    });
};

The issue with your type validation error is likely due to the fact that the onSubmit event handler receives the event parameter. If you intend to make use of this parameter, you should modify your function signature as follows (where e represents the event object):

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
...

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

CanvasJS showcasing a variety of pie charts

I need to generate multiple pie charts for a website, but I'm struggling with the idea of dynamically rendering them based on the required quantity. I know that I will have to create a maximum of 28 pie charts at once. My initial approach involves man ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

"Unleashing the power of custom servers to tap into the rendered HTML of Next

In my quest to serve a server-side generated page as a file using next.js, I decided to extract the rendered content within a custom server.js file: const express = require('express'); const next = require('next'); const port = parseIn ...

Navigating with Angular 2: Expressing HTML 5 Routing Challenges

I'm currently working on a simple web application using Express 4 and Angular 2. The only Angular 2 specific aspect in this project is the utilization of its HTML5 router. Let me walk you through how the routing works in this app: There are two prim ...

Updating the value property of an object within a loop dynamically in React

At the moment, I am utilizing an array of objects called "mainArr" as shown below, I have implemented a loop inside a function to filter object properties, but I want to dynamically replace obj.name with obj."param" based on the parameter passed. Both nam ...

Exploring the world of Next.js version 9.3 and beyond with the exciting addition

As a beginner with Next.js, I am seeking guidance on utilizing getStaticPaths and getStaticProps within catch-all routes. Many blog starters for Next.js 9.3+ focus on single-level blog posts (such as /posts/post-1.md, /posts/post-2.md, etc.), but I am stru ...

Retrieve the keys stored within a complex array of objects

I am searching for a function that can transform my data, specifically an array of objects with nested objects. The function should only include keys with immediate string/number/boolean values and exclude keys with object/array values. For example: [ { ...

"Seeking advice on how to nest a service provider within another one in AngularJS 2. Any

I am faced with a product and cart list scenario. Below is the function I have created to iterate through the cart list and retrieve the specific product using its ID. getCartList(){ this.cart = CART; this.cart.forEach((cart: Cart) => ...

Incorporating Dynamic Javascript: A Step-by-Step Guide

I came across a select object that looks like this: <select id="mySelect" onchange = "start()" > <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> < ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

Why do my paths encounter issues when I alter the manner in which I deliver my index.html file?

I recently made a decision to change the method of serving my index.html file from app.use('/', express.static(__dirname + '/..')); to app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/../index.htm ...

Problem with ng-include in ng-view templates

Directory Layout: --app --partials --navbar.html --submit --submission.html index.html Using ng-include in submission.html: <ng-include src="'app/partials/navbar.html'" ></ng-include> However, the navbar does not displa ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...

Sending basic HTML from Express.jsSending simple HTML content from an Express.js

Within my index.html document, I have the following: <input name='qwe'> {{qwe}} I am looking to send {{qwe}} in its literal form, without it being replaced by server-populated variables. How can I achieve this? My initial thought was to ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

Is there a way to automate the distribution of tasks to users in order to ensure that each user receives an equal number of assignments?

I'm in the process of developing an automated task manager that assigns tasks to users based on their role. Currently, I'm randomly selecting a user with the same role as the task from the list of users and assigning the task to them using math.r ...

I am interested in sharing photos by posting them on the public folder link and incorporating them into a React app

Just finished building my react portfolio website and now I'm looking to share it for free using platforms like Github Pages or other similar options. The only issue is that I have a few things to consider - my public folder with project images and al ...

How come a React form is not recognizing input on just three specific fields?

In the React app I'm working on, everything was functioning properly until I added more fields to a form. For some reason, "First Name", "Middle Name", and "Last Name" inputs are unresponsive when I try to type in them. I followed the same process to ...

How can we efficiently link data to custom objects (models) within a different class while fetching data from the server using the http.get() method in Angular CLI?

Currently in the process of developing an Angular-Cli application that involves multiple models with relational data tables. When fetching data from the server, I need to map this data to corresponding model objects. I've experimented with creating a ...