Executing the useFormState dispatch using the provided data

I am facing a challenge in validating form data before sending it to a server. I want to set the form action property to a function that can validate the data on the client side and then trigger the formAction if everything checks out. However, I am struggling with how to pass data from the form action to the function and back to the formAction function. My project uses next.js with typescript, and I would like to utilize a form state with a formState variable. The issue arises when calling formAction without any arguments, even though I need to provide my form data. How can I effectively pass data to the validateData function and subsequently to formAction? I am currently using next.js version 14.2.5, along with react and react-dom 18.2.

Below is a simplified version of the problem I am encountering.

"use client";
import { useFormState } from "react-dom";
import farServerFunction from "./func.ts";

export default function Page() {
  const [formState, formAction] = useFormState(farServerFunction, null);
  const validateData = (data: FormData) => {
    const name = data.get("name") as string;
    if (name.length < 5) {
      alert("Name must be at least 5 characters long.");
      return;
    }
    formAction(data); // Expected 0 arguments, but got 1
  }
  return <form action={validateData}>
    <input type="text" name="name" />
    <button type="submit">Submit</button>
  </form>;
}

I have attempted to research this issue online, including using chatGPT and consulting documentation, but I still find it confusing and lacking sufficient clarity.

Answer №1

Upon further investigation, it appears that useFormState is able to adjust based on the function provided to it. If you provide a test function without any parameters initially, it will not expect any arguments. To resolve this issue, define the function with the required arguments (e.g. "_: any, formData: FormData"), so that when you call formAction with an argument, no errors will be triggered.

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

Navigating the ins and outs of troubleshooting NextJS during the build phase

I am encountering an issue with my NextJS app that has a path containing over 50,000 pages. While the app runs fine with 'npm run dev', I face an error during the build process: 'TypeError: Cannot read property 'page' of undefined ...

Discover how to extract response headers utilizing the capabilities of the Microsoft Graph API in conjunction with the MSGraphClientFactory

I have a question that is very similar to this post: How to retrieve response headers using Microsoft Graph API The main difference I noticed (correct me if I'm wrong) is that I am utilizing MSGraphClientFactory.getClient() from '@microsoft/sp-h ...

"Enhancing Development with Visual Studio 2015: Leveraging tsconfig.json and Typescript 1.8.10

According to the Typescript wiki, with the release of Typescript 1.8, there is a significant enhancement in Visual Studio 2015 for 'Improved support for tsconfig.json' (emphasis added by me): With TypeScript 1.8, tsconfig.json files can now be ...

Dynamic Images with Next.js

Currently, I am utilizing next.js and attempting to dynamically retrieve images in the following manner: {list.map((prod) => ( <div className={styles.singleProduct}> <h6>{prod.Brand.toUpperCase()}</h6> <p&g ...

After updating to Angular 10, the class constructor can only be called using the 'new' keyword

After following the official procedure at update.angular.io, I successfully upgraded my app from Angular 9 to Angular 10 using ng update. However, upon completion, I encountered numerous errors such as: ERROR Error: Uncaught (in promise): TypeError: Cl ...

Update the style of a div within an iframe in React

I'm currently developing a project in Next.js and I've added an iframe within a component. The issue I'm facing is that I need to customize the style of a specific div inside the iframe, but I'm having trouble targeting the div with the ...

Combine a list with an observable list

Consider having 3 different types of lists - two basic lists and one observable list. The challenge arises when you need to combine a non-observable list with the observable one. The current approach may seem unconventional for observables. listToMerge ...

Is the Google Maps Javascript API compatible with Ionic 2?

Hi everyone, I hope you're all doing well :) In my development of a basic application using Ionic Framework with Google Maps (Map + Places SearchBox), everything is working smoothly until I encounter an issue when trying to search for an address (e.g ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Ways to pass functions as properties to a React custom modal?

I'm currently working on a React login page setup. The login functionality is embedded in a Modal using the React-Modal library. When a user presses the login button, data is supposed to be sent to a Custom Modal as props to display a notification win ...

The specified property cannot be found on the Window type and the globalThis typeof

I encountered an error in my Electron-React-Typescript app that reads: Property 'api' does not exist on type 'Window & typeof globalThis'. window.api.send('open-type-A-window', ''); The issue seems to be related ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

Images in Next.js are appearing as broken images on certain pages

When using Next Image, it functions correctly on files located in the root of the page folder. However, images appear broken when accessed from the sub-folder within the page folder. ...

The API endpoint code functions perfectly in Express, but encounters an error when integrated into Next.js

Express Code: app.get('/', async (req, res) => { const devices = await gsmarena.catalog.getBrand("apple-phones-48"); const name = devices.map((device) => device.name); res.json(name); }) Nextjs Code: import {gsmarena} ...

"Exploring the seamless integration of Next.js and Material UI for stunning web

I have encountered an issue while using Next.js and Material-UI(@mui/core) to build a website. Everything works perfectly when I run it with next dev, but the styles get messed up when using next build && next start. In addition to Material-UI, I ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

What sets apart `tsc --build --clean` from `rm -rf *.js` command?

I'm curious about the tsc command with the arguments --build --clean, which is used to clean/remove the generated .js files from the Transpiler (tsc). What makes this command special or significant? If I simply need to delete all the .js files, I can ...

Avoid automatic restart of NestJS server upon modifying specific directories

When running my application in watch mode using the nest start --watch command, the server automatically restarts whenever a source file is changed. While this behavior is expected, I am looking for a way to exclude certain directories or files from trigg ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Callback separated from the properties of the component

My journey with TypeScript and Angular 2 is just beginning. I encountered an unusual issue with the Cordova Camera Plugin: it seems like callbacks are not properly connected to the rest of my component! Below is a snippet of the code causing this problem ...