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

beginning with --keepAliveTimeout the following

I was following the documentation at https://nextjs.org/docs/api-reference/cli and I have my script defined like this: "scripts": { "dev": "next dev", "build": "next build", "start": & ...

I encountered an issue while attempting to retrieve data using route parameters. It seems that I am unable to access the 'imagepath' property as it is undefined

Is there a way to access data when the page loads, even if it is initially undefined? I keep getting this error message: "ERROR TypeError: Cannot read properties of undefined (reading 'imagepath')". How can I resolve this issue? import { Compone ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Transforming TypeScript snapshot data in Firebase Cloud Functions into a string format for notification purposes

I've encountered the following code for cloud functions, which is intended to send a notification to the user upon the creation of a new follower. However, I'm facing an issue regarding converting the snap into a string in order to address the er ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

What is the best way to integrate ContextualMenu with Persona in Office Fabric UI React?

Currently, I am utilizing Office Fabric UI React to work on a project. My goal is to implement a ContextualMenu in conjunction with the Persona object. In this particular example, I am demonstrating how ContextualMenu can be applied directly to differ ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

The issue of saving Rails input from an Angular2 front end has been causing some trouble

Currently, I am in the process of developing a front-end application using Angular 2 that retrieves data from a Rails 5 API. This specific application serves as a network inventory tool. One particular feature of this app is an Asset-form in Angular2 whic ...

Exploring the differences between req.params and req.query when working with Next.js dynamic API routes

I am perplexed by the difference in accessing params in my Next.js API routes compared to traditional express routes. In order to access a specific dynamic route ID, I find myself using req.query instead of the usual params. Is this the preferred method fo ...

Having trouble getting the tailwindcss Google font link tag to apply properly

When I use the @import in the tailwind css file, it works fine. However, when I try to add the font using the <link> tag in _document.jsx, it fails to work properly. In Chrome dev tools, it shows that the classes are applied but the fallback font is ...

One method of extracting an object from an array using a parameter function is by utilizing the following approach

I am searching for a specific object in an array based on the user-provided ID. var laptops = [{ "name": "Firefox", "age": 30, "id": "ab" }, { "name": "Google", "age": 35, "id": "cd", "date": "00.02.1990" }, { "na ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Nonconforming Typescript argument specification

I've been struggling to pass this TypeScript array to a function. Despite trying multiple parameter types in an attempt to get it to compile, none of them have worked so far. Here is the array in question: var driverTally = [ { dr ...

Error encountered in Node.js OpenAI wrapper: BadRequestError (400) - The uploaded image must be in PNG format and cannot exceed 4 MB

Attempting to utilize the OpenAI Dall-e 2 to modify one of my images using the official Nodejs SDK. However, encountering an issue: This is the snippet of code: const image = fs.createReadStream(`./dist/lab/${interaction.user.id}.png`) const mask = fs.c ...

What is the best way to combine the attributes of multiple objects within a union type?

I have a clearly defined schema type Schema = { a: { a: 1 } b: { b: 2 } } I am in need of a function that can generate objects that adhere to multiple schemas. function createObject<K extends keyof Schema>(schema: Array<K>, obj: Sche ...

Developing step code for CucumberJS Scenario Outlines

In my feature file, I have the following scenario outlined for testing colors: Feature: Color feature @test Scenario Outline: Test color Given the first color is <COLOR_ONE> And the second color is <COLOR_TWO> ...

The sequence of styles injection in JSS and Material-UI varies from development to production environments

I am currently experimenting with Material-UI (https://material-ui.com/) in combination with NextJS (https://nextjs.org/), utilizing the JSS solution for styling. While everything appears to be functioning as expected in my local environment, I am encount ...

Following mouse element delay issue in the latest directory of a Next.js 13 application

I'm working on a project where I want to create an element that follows the mouse as it moves across the screen. I decided to use framer motion for the animation and found a helpful example in their documentation: Check out this example from framer mo ...

Next-generation Keystone mutation customization

Could someone please help me troubleshoot why my mutation is not functioning properly? I am using a Keystone-next backend, apollo-boost, and next.js. Despite having the fields in the state and setting them as variables, they are not being sent to the backe ...

Is it possible to utilize getInitialProps in both _app.js and in individual pages within the application?

I am currently developing my first significant NextJS application. Instead of hardcoding the left navigation data directly into the app, I have set it up to pull in JSON data. This allows me to make minor changes to the site's navigation without havin ...