What could be the reason for the react hook form failing to capture the data upon submission?

I am struggling to access the props' value after clicking the button, as it keeps returning undefined. My goal is to display the years of service and profession details based on the user's selection.

return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Box display="flex" flex={1} flexDirection="column">
        <Box padding={1}>
          <FormControl>
            <Controller
              control={control}
              id="isUserEmployed"
              name="isUserEmployed"
              defaultValue={isUserEmployed.toString()}
              render={({ onChange }) => (
                <RadioGroup
                  onChange={({ target: { value } }) => {
                    onChange(value);
                  }}
                  defaultValue="hasjob"
                >
                  <FormControlLabel
                    value="hasjob"
                    control={<Radio color="primary" size="small" />}
                    label="Has Job"
                  />
                  <Box>
                    <Autocomplete
                      disablePortal
                      fullWidth
                      options={(() => {
                        if (profession === "Teacher") return jobTeacher;
                        if (profession === "Developer") return jobDeveloper;
                      })()}
                      getOptionLabel={(option) => option.value.toString()}
                      renderInput={(params) => (
                        <TextField {...params} variant="standard" />
                      )}
                      onChange={onProfessionChange}
                      autoHighlight
                      clearOnEscape
                    />
                  </Box>
                  <FormControlLabel
                    value="noJob"
                    control={<Radio color="primary" size="small" />}
                    label="No Job"
                  />
                </RadioGroup>
              )}
            />
          </FormControl>
          <Button
            size="large"
            color="primary"
            variant="contained"
            type="submit"
          >
            Enter
          </Button>
        </Box>
      </Box>
    </form>
  );
}

https://codesandbox.io/s/small-dew-kdmmfu?file=/src/App.tsx

This implementation utilizes react-hook-form version 6

Answer №1

When you destructure data in the onSubmit function, you may encounter an issue where undefined is logged in the console. To resolve this, consider removing the destructuring and adjusting the onSubmit function as shown below.

const onSubmit = (data : any) => {
    console.log("Here");
    console.log(data);
  };

The variable yearsOfService is managed using the useState hook instead of react-hook-form, which means it may not be included in the data object. If you need yearsOfService to be tracked by RHF, try placing the AutoComplete outside of the RadioGroup, render it with a Controller, and provide its default value to the useForm hook.

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

I am facing difficulty in deploying my Next.js app with Firestore

Having trouble deploying my application using npm run build, Vercel, or another service. It works fine locally without showing any errors. I am using Firebase, Next.js, and TypeScript. The issue seems to be related to getStaticProps. When requesting data, ...

Utilizing internationalization and next/image in next.config.js alongside TypeScript

Currently, I am in the process of developing a miniature application using TypeScript within NextJS now that support for TypeScript comes standard in Next.js. Additionally, my aim is to integrate two recently introduced features: Image Component and Image ...

"Sequencing http.get requests in Angular 2 using

In my service, I have a series of http.get requests structured as follows: constructor(private http:Http) {} getDetails(sysID:string){ var details; this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0] ...

Using React Material UI to create multiple collapse components

Currently, I am facing an issue where all the collapses in my list are linked to one state for "open." This means that if I open one list, all the other lists also open. I am looking for a way to keep the collapses separate from each other without needing ...

Signatures overburdened, types united, and the call error of 'No overload matches'

Consider a TypeScript function that takes either a string or a Promise<string> as input and returns an answer of the same type. Here's an example: function trim(textOrPromise) { if (textOrPromise.then) { return textOrPromise.then(val ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

Extract data from Angular2 class

I am having trouble with the data binding of {{value}}. Here is a straightforward example: app.component.ts import {Component, OnInit} from "@angular/core"; @Component({ selector: "app", templateUrl: "./app/app.html" }) ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

Unable to assign dynamic key to Vue 3 directive for object property

Currently, I am utilizing the maska npm package to mask input fields in Vuetify. Within my setup, I have an array of masks that I make use of: export const Masks = { hour: { mask: "##:##", eager: true }, host: { mask: "#00.#00.#00.# ...

Issue: An error occurred while trying to parse JSON data in TypeScript due to an undefined 'description' property

Encountering an error message when attempting to retrieve the description attribute from the following Sample Json. Error: TypeError: Cannot read property 'description' of undefined when trying to access json data in typescript import {Age ...

Could you please explain the purpose of the muiName property and provide guidelines on when it must be assigned to Material-UI components?

The official documentation for the material-ui library provides an example showcasing the usage of the AppBar component, which can be found here. The example code snippet is as follows: import React, {Component} from 'react'; import AppBar from & ...

A TypeScript function that returns the ReturnType of a specific callback function

Is it possible to define an annotation for a function that accepts a callback, and have the function return type determined by the callback's return type? // Suppose the callback takes a number as argument function processCallback(cb: (arg:number) =&g ...

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 ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

Erase the destination pin on Google Maps

I am currently working on a project that involves displaying hit markers on google maps along with a route from start to finish. Although I have successfully displayed the route, I encountered an issue where both the origin and destination have identical ...

I am attempting to retrieve custom cellRendererParams within the CustomCellRenderer class

I'm currently working with Ag-Grid in my angular application and am trying to implement a custom cell renderer. The tutorial I followed uses ICellRendererParams for the parameter type passed to the init event. agInit(params: ICellRendererParams): void ...

In version 6.x of mui/x-date-pickers, a common query arises: How can the year and month format be customized on the date picker

<LocalizationProvider dateAdapter={AdapterLuxon} adapterLocale={"ja"} localeText={jaJP.components.MuiLocalizationProvider.defaultProps.localeText}> <DatePicker {...field} label="testla ...

Utilizing the output of one function as an input parameter for another function: A guide

Having this specific shape const shape = { foo: () => 'hi', bar: (arg) => typeof arg === 'string' // argument is expected to be a string because foo returns a string } Is there a way to connect the return type of foo to the ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...