Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts a JSON Array.

However, I am facing issues in retrieving the selected items from the table. Here is my attempt after following some tutorials:

// ...

const [selectedKeys, setSelectedKeys] = React.useState(new Set([]));

return (
    <section className="flex flex-col items-center justify-center gap-4 py-8 md:py-10">
      <div className="inline-block max-w-lg text-center justify-center">
        <h2 className={subtitle({ class: "mt-4" })}>
          Please select the reviews to be removed:
        </h2>
      </div>

      <div className="flex flex-col gap-3">
        <Table
          color="primary"
          selectionMode="multiple"
          aria-label="Example static collection table"
          isStriped
          selectedKeys={selectedKeys}
          onSelectionChange={setSelectedKeys}
        >
          <TableHeader columns={columns}>
            {(column) => <TableColumn key={column.key}>{column.label}</TableColumn>}
          </TableHeader>
          <TableBody items={reviews}>
            {(item) => (
              <TableRow key={item.key}>
                {(columnKey) => <TableCell>{getKeyValue(item, columnKey)}</TableCell>}
              </TableRow>
            )}
          </TableBody>
        </Table>
);

// ...

The item keys are numbers as per all tutorials, including those in the NextUI documentation.

In VS Code, I see this message regarding the onSelectionChange method:

Type 'Dispatch<SetStateAction<Set<never>>>' is not assignable to type '(keys: Selection) => void'.
  Types of parameters 'value' and 'keys' are incompatible.
    Type 'Selection' is not assignable to type 'SetStateAction<Set<never>>'.
      Type 'string' is not assignable to type 'SetStateAction<Set<never>>'.ts(2322)
selection.d.ts(39, 3): The expected type comes from property 'onSelectionChange' which is declared here on type 'IntrinsicAttributes & MergeWithAs<Omit<DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>, "ref">, Omit<...>, TableProps, "table">'

When I try to run it, I encounter this message:

This situation is quite frustrating for me.

Answer №1

let [chosenItems, setChosenItems] = useState<Selection>(new Set<string>())

<Table 
  aria-label="Interactive table with dynamic content"
  selectionMode="multiple"
  onSelectionChange={(selected) => {
    setChosenItems(selected)
  }}
>

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

Tips for creating a reusable component using react-hook and yup?

Here is the code I have written: https://github.com/robokonk/react-hook-component/blob/main/pages/index.tsx I am working on creating a reusable input component with validation. Can anyone suggest corrections to improve it? Currently, I am facing an issue ...

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Having trouble integrating Socket.io with Express.js?

I'm currently attempting to connect socket.io with express.js: var socket = require('./socket_chat/socket.js'); var express = require('express'), app = module.exports.app = express(); var io = require('socket.io&apo ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

Utilize Javascript/jQuery to play individual HTML audio files sequentially

On my website, each keyboard key is associated with an audio file. When a letter key from A to Z is pressed, the corresponding audio file is played. For all other keys (excluding ESC), a random audio file out of the 26 available is played. However, if mult ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

When using NextJs along with Framer-motion, a warning may appear stating "Prop `className` did not match."

I created this AnimatedLetter component using framer motion to animate each letter individually from a string, making them appear from the bottom with a stagger effect. However, I encountered the following error: Warning: Prop style did not match. Server: ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

ajax always returns the same value, even when the input value is different

Each time I click on a different value, the console.log keeps giving me the same value. view image description I have checked the HTML code and found that even though each value attribute is different, it still returns the first value of the attribute. vi ...

Exploring Entries in Several JSON Arrays

In my current project, I have successfully generated JSON using JSON-Simple. Query: I am seeking guidance on how to extract specific elements like "Sentiment," "score," and "review" from this JSON array. Although I have referred to a helpful resource he ...

Attempting to retrieve the value from a nested table within a table row using Jquery

<tr role="row" class="odd"> <td style="background-color:white"> <table> <tbody> <tr data-row-id="22"> <td id="pid"><input type="checkbox" class="sub_chk" value="8843" data-id="22">< ...

Ensuring Radiobuttons are Selected on a Page After Clicking the Submit Button

Seeking assistance with this issue: I am working on a page that includes radio buttons: <label>Delivery type:</label> <input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick=""><label class="label" ...

Guide to creating seamless integration between AngularJS routing and ExpressJS routing when using html5mode

Yesterday, I posted a question on stackoverflow about my webpage's CSS and JavaScript not including after a refresh. I discovered that it was caused by html5mode, but I have been searching for a solution since then with no luck getting an answer. My ...

Create PDF and Excel files using Javascript on the client side

Are there any client-side Javascript frameworks that are comparable to Jasper Report in Java? I need to be able to generate both PDF and Excel files on the client side (browser) without relying on server-side processing. While I've come across Ja ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

An issue with asynchronous execution in Protractor

I have been using and learning protractor for over a month now. Despite the documentation stating that Protractor waits for Angular calls to complete (http://www.protractortest.org/#/), ensuring all steps are executed synchronously, I have not found it ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Getting variables from different functions in Python can be achieved by using the return

I am trying to implement a feature where I can fetch a search term from the function getRandomVideo() and then use it in a jQuery statement. For example, if I get "Beethoven" as the search term from the variable searches, I want to use it to retrieve JS ...

AngularJS powered edit button for Laravel route parameter

I have a data list that needs to be edited using an edit button. When clicking the edit button, I need to send the ID to a Laravel controller in order to fetch the corresponding data. The initial listing was created using Angular JS. <a class="btn" hr ...