Issue: The type 'Error: (data: string) => number' cannot be assigned to type '() => void'

Encountering an issue while attempting to add a string to an array. Any assistance would be welcome.

Error message @ onClick:

Type '(productName: string) => number' is not compatible with type '() => void'.ts(2322) types.d.ts(59, 5): The expected type is derived from property 'onClick' which is defined here on type 'IntrinsicAttributes & ButtonProps'

The relevant code snippet is provided below

const productList : string[] = [];
const handleClick = useCallback((productName:string) => productList.push(productName),[]);

JSX

<Button primary onClick={handleClick}>Add Product</Button>

Answer №1

How can the button determine which product you have selected?

The solution is to create a new function for each button that will pass in the specific product that was clicked.

For instance:

function Button({ onClick, children }: { onClick: () => void, children: React.ReactNode }) {
  return <button onClick={onClick}>{children}</button>
}

function ProductList() {
  const productList : string[] = []; // this needs to be stored as state
  const handleClick = useCallback((productName:string) => productList.push(productName),[]);
  
  return <>
    <div>
      Product A
      <Button onClick={() => handleClick('A')}>Add Product</Button>
    </div>
    <div>
      Product B
      <Button onClick={() => handleClick('B')}>Add Product</Button>
    </div>
  </>
}

View playground


It is important to note that productList should be handled as state rather than just a regular variable. If you simply add items to an array without managing it as state, React will not detect the changes and won't re-render any components. This is a separate issue to consider but worth mentioning.

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

Guidelines for properly storing user data post-login in Nuxt3

When a user logs in, I need to store their data for future use. I have middleware set up on the "/page" page to check if the user is logged in, and if so, it allows them through. However, I notice that the user data is lost when the page is refreshed. In t ...

Attempting to call a function with a template variable is not allowed

@Component({ selector: 'modal', ... }) export class SimpleModal { modalOpen: boolean; isModalOpen(): boolean { return this.modalOpen; } } <modal #modalRef> <div *ngIf="modalRef.isModalOpen()">...</div> </mo ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...

Creating a TypeScript function that automatically infers the type of the returned function using generics

Suppose I want to execute the generateFunction() method which will yield the following function: // The returned function const suppliedFunction = <T>(args: T) => { return true; }; // The returned function // This is how it can be used suppli ...

The nest build process encounters errors related to TypeScript in the @nestjs/config package, causing it

Encountering several issues related to @nestjs/config, causing the npm build command to fail. However, npm run start:dev is still functional despite displaying errors. See below for screenshots of the errors and environment: https://i.sstatic.net/Wxkkn.png ...

TS2304 TypeScript (TS) Unable to locate the specified name

Encountering an error message stating Cannot find name 'Record'. Do I need to install a specific package for this class? Severity Code Description File Project Line Suppression State Error TS2304 (TS) Cannot find name 'Record ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

Error detected in Ionic socket.io chat page

I'm encountering a minor issue with my chat page. I'm trying to create a chat application, and everything is working fine except for the chat button, which causes the app to crash. Being a beginner, I might be missing something obvious. The issue ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Typescript's date function offers a variety of useful features

Can anyone help me create a function that formats a date string for sorting in a table? The date is in the format: 08.04.2022 16.54 I need to convert this to a number or date format that can be sorted. I'm new to TypeScript and could use some guida ...

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...

What makes the type definition of `promise.all` particularly effective in this scenario?

While working on a question from type-challenges repository, I encountered this issue. The code below fails in case 3: declare function PromiseAll<A extends readonly unknown[]>(values: A): Promise<{ -readonly [key in keyof A]: Awaited<A[key] ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

Is it possible to link observables in this manner? I've created a solution, but I'm uncertain if it's the most optimal approach

I have created a custom pipe in Angular to transform data retrieved from an observable using the async pipe. Here is the HTML code snippet: <div class="meeting-dtls-sub-div" ***ngFor="let meeting of meetingData$ | async | hzCalendarFilter ...

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...

Encountering the following issue: "ERROR TypeError: Argument is required in IE 11"

The code below is functioning properly in all internet browsers except for IE11. When running the code in IE, an error is thrown stating "ERROR TypeError: Argument not optional." The project being developed is using Angular 10. private togglePageClass(mod ...