I have a problem with setState in Select component (shadcn/radix-ui)

489 Views Asked by At

Overview

In our project, we encounter an issue with the page-size dropdown feature. Presently, we utilize state management for the select component, initializing it with an object as the default value. Here's a snippet of the current implementation:

const [page, setPage] = useState({ label: '25', value: '25' });

Code view

Below is the code snippet for the component responsible for the page-size dropdown:

export default function SelectDropDown({
  options,
  placeholder,
  ...props
}: TProps) {
  return (
    <Select {...props}>
      <SelectTrigger>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {options.map((option) => (
          <SelectItem value={option} key={option.value}>
            <p className="cursor-pointer text-neutral-600   hover:bg-primary-50 ui-selected:bg-primary-75 ui-selected:hover:bg-primary-75 ui-selected:text-primary-200">
              {option.label}
            </p>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

The component is employed within the header section, as demonstrated here:

export default const Header = () => {
  const [page, setPage] = useState({ label: '25', value: '25' });

 const perPageDropDownOptions = [
    {
      label: '25',
      value: '25',
    },
    {
      label: '50',
      value: '50',
    },
    {
      label: '100',
      value: '100',
    },
    {
      label: '150',
      value: '150',
    },
  ];

  React.useEffect(() => {
    console.log('page', page);
  }, [page]);

  return (
    <div className="w-[200px]">
      <Select
        options={perPageDropDownOptions}
        onValueChange={setPage}
        defaultValue={page.value}
      />
    </div>
  );
};

Problem:

The issue arises when different values are selected. The state, instead of being set as an object as initially defined ({ label: '25', value: '25' }), gets assigned a single value such as 25 or 100. This discrepancy is evident from the useEffect log.

Desired Solution:

We aim to ensure that the state retains an object structure similar to { label: '100', value: '100' } when updated with a different value selection.

How can we achieve that ?

. . . . . . . . . . .

0

There are 0 best solutions below