Encountering type errors in NextJS with TypeScript

I am facing an issue while trying to run this function:

"use server";

export const addProduct = async (formData: FormData, imageUrl: string) => {
  const productName = formData.get("productName")?.toString();
  const description = formData.get("description")?.toString();
  const location = formData.get("location")?.toString();

  if (!productName || !description || !imageUrl || !location) {
    throw Error("Missing required fields");
  }
};

<form className="flex flex-col gap-4 text-lg" action={addProduct(imageUrl)}>

Errors:

Type '(formData: FormData, imageUrl: string) => Promise<never>' is not assignable to type 'string | ((formData: FormData) => void) | undefined'. Type '(formData: FormData, imageUrl: string) => Promise<never>' is not assignable to type '(formData: FormData) => void'. Target signature provides too few arguments. Expected 2 or more, but got 1.

No matter how many arguments I add to the addProduct function, the error persists, possibly due to incorrect types being used.

Answer №1

"createItem" is a method that does not return anything, also known as void.

You're currently using action={createItem(...)}, which means you are passing the result of the "createItem" method to "action", not the actual method itself. To make it work correctly, you need to pass the method itself to the form so that the form can invoke it when needed.

If the createItem method did not require any arguments, you could simply use action={createItem}. However, since you need to provide the imageUrl, this approach won't work.

One solution is to use an inline function:

<form action={(data: FormData) => createItem(data, imageUrl)}>

Another option is to curry the createItem method:

const createItem = (imageUrl: string) => async (formData: FormData) => {
  const itemName = formData.get("itemName")?.toString();
  const description = formData.get("description")?.toString();
  const location = formData.get("location")?.toString();

  if (!itemName || !description || !imageUrl || !location) {
    throw new Error("Required fields missing");
  }
};

Then:

<form action={createItem(imageUrl)}>

In this case, calling createItem(imageUrl) will now return a function that only takes FormData as input, matching what the form tag expects.

You might want to reconsider why imageUrl is passed as an argument. Storing it in state and accessing it within the method may be more efficient than expecting it as a parameter.

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

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

Executing a function by click event using the onclick attribute from a file located in the public directory of my project (Next

I'm new to using Next.js and I have a question about how to utilize onclick to execute a function from an external file located in my public folder. Below is my index.js file: import Head from "next/head" import Script from "next/scrip ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

What is causing unexpected behavior when one service calls another service?

Let's say I make a call to a service that returns an observable, and if it doesn't encounter any errors, then another service should be called which also returns an observable. What I tried doing is calling both services separately, one after th ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

The use of dangerouslySetInnerHTML causes the page layout to stretch, expand, or grow in size

I am currently working on my NextJs app, where I'm utilizing CosmicJs as a headless CMS to showcase content on the webpage. Within the layout of my page, I have structured it with 3 columns, and the content pulled from the CMS is meant to be displaye ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

The module 'json-stringify-safe' could not be located

Encountering an issue while executing the command - ionic serve The code was functioning properly on a different system but seems to be causing trouble for me at the moment. ...

I encountered an unhandled rejection error of type TypeError when trying to read properties from an undefined value, specifically when attempting to read '__emotion_real'

I encountered an issue while developing a next js application: unhandledrejection typeerror: cannot read properties of undefined (reading '__emotion_real') This problem arose after I updated the next js and emotion libraries: "@emotion/bab ...

TS7016: No declaration file was found for the module named 'rxjs'

I recently updated my Angular App dependencies and successfully installed them. However, I am now facing an issue with 'rxjs'. The IDE returned the following error: TS7016: Could not find a declaration file for module 'rxjs'.'C:/ ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more. ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...