How can we determine the type of InertiaFormProps in Laravel Inertia?

I have a webpage with a useForm hook implemented, featuring a multi-step form split into separate components.

Here's an example:


    export default function create(){
    
      const form = useForm({
        name: '',
        content: '',
        is_published: 0,
        some_more_fields_here
      });
    
    
    return (
    <div>
    <GeneralPageInformation form={form} />
    
    
    <SeoInformation form={form} />
    </div>
    )
}

The form object returned by useForm appears as follows:

 InertiaFormProps<{name: string, content: string, is_published: number, rest of your fields}>

My attempt at defining this was:

interface IGeneralPageInformation {
  form: InertiaFormProps;
}

Although giving access to properties like form.processting and form.recentlySuccessful,

the keys such as name and content were not visible when using functions like

form.setData('all available keys should show up here))

I could manually include the keys like so:

interface IGeneralPageInformation {
  form:  InertiaFormProps<{name: string, content: string, is_published: number, resf of the fields}>
}

However, this manual approach is not very "scalable" since every form would need editing whenever changes occur.

Answer №1

When working with Vue 3,

<script setup lang="ts">
import { InertiaForm, useForm } from "@inertiajs/inertia-vue3"

const form: InertiaForm<{
                title: string,
                category: string,
                types: Array<string | number>
            }> = useForm({
                title: "",
                category: "",
                types: [],
            })
</script>

Answer №2

To implement this in React, follow these steps:

import { InertiaFormProps } from '@inertiajs/react/types/useForm'
import { useForm } from '@inertiajs/react'

interface FormStructure {
  email: string
  password: string
}

const CustomReactForm = () => {
  // Use your defined structure as a generic like so 👇
  const { data, setData }: InertiaFormProps<FormStructure> = useForm({
    email: '',
    password: '',
  })

  return (
    <form>
      <input
        id='email'
        type='email'
        onChange={(e) => setData('email', e.target.value)}
        value={data.email}
      />
      <input
        id='password'
        type='password'
        onChange={(e) => setData('password', e.target.value)}
        value={data.password}
      />
    </form>
  )
}

export default CustomReactForm

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

Quirky happenings in Typescript

TS Playground function foo(a: number, b: number) { return a + b; } type Foo1 = typeof foo extends (...args: unknown[]) => unknown ? true : false; // false type Foo2 = typeof foo extends (...args: any[]) => unknown ? true : false; // true What is ...

Can someone assist me in creating mongoose models?

Currently, I am focused on managing products and categories These are the two types I have created: type Category = { parent: Category | null; // Is this acceptable? name: String; }; type Product = { categories: Category[]; name: String; ...

Why does Angular throw a length-related error, while I am able to retrieve the length using console log if needed?

It appears that Angular is not receiving the correct data type it expects, yet the lack of errors in the terminal is puzzling. However, the console output states: https://i.stack.imgur.com/1xPsg.jpg If the length property can be detected (highlighted in ...

A method for increasing a counter using only an instance of a class or function without accessing its methods or properties in Javascript

Looking at the task ahead, let increment = new Increment(); I have been tasked with creating a Javascript class or function called Increment in order to achieve the following: console.log(`${increment}`) // should output 1 console.log(`${increment}`); ...

How can we include additional types for external npm packages in a React TypeScript project?

Recently, I encountered an issue while using the react-microsoft-login package from npm. I included a button in the children property and received a typescript error stating that "property 'children' does not exist on type 'intrinsicattribut ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

Detecting changes in Angular when the @Input() value remains the same

I have created an Angular Custom scroll directive that utilizes an @Input() to pass an HTML element as a parameter, allowing the scrollbar to move to that specific element. However, I've encountered an issue where if I pass the same HTML Element mult ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

Leveraging React Hooks to display a dynamic pie chart by fetching and mapping data from an API

I have a task where I need to fetch data from an API that returns an object containing two numbers and a list structured like this... {2, 1 , []} The project I'm currently working on utilizes 'use-global-hook' for managing state in Redux. T ...

"An issue has been identified where TSLint and VSCode fail to display red underlines in

I am currently working on a single .ts file where I am experimenting with configuring tslint and tsconfig. To test the configuration, I intentionally added extra spaces and removed semicolons. Despite running the command tslint filename.ts and detecting e ...

Issue encountered while conducting tests with Jest and React Testing Library on a React component containing an SVG: the type is not recognized in React.jsx

In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this: import ChevronLeftIcon from './chevron-left.svg' The issue arises when running a test on a component that includes an SVG import, ...

Is it possible to pass a different variable during the mouse down event when using Konva for 2D drawing?

I am trying to pass an additional value in a mouse event because my handleMouseDown function is located in another file. stage.on('mousedown', handleMouseDown(evt, stage)) Unfortunately, I encountered an error: - Argument of type 'void&apos ...

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

What is the process of transforming two forms into components and then integrating those components into a view in Angular 5?

Currently, I have two forms running smoothly on the same component as shown in InfoAndQualificationComponent.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

What was the process for implementing the lexer and parser?

My journey into the depths of programming languages led me to explore how TypeScript is implemented, prompting me to venture into its Github repository. Within the language's source code under /src/compiler, I stumbled upon intriguing files like scan ...

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

The 'string[]' type cannot be assigned to the 'string | ParsedUrlQueryInput | null | undefined' type in Next.js and Typescript

I'm facing an issue while attempting to transfer an array of strings from one page to another in Next.js using <Link href={{ pathname: "/model", query: data }}>. The problem arises when the query parameter is red underlined: Type &apos ...