NextUI Select component selectedKeys value becomes undefined when the value comes from an async API call

1.1k views Asked by At

I am passing the API call result to another component. The component from NextUI seems fine when passing the props but the encounters an issue when assigning the value to selectedKeys property then the succeeding fields do not work properly.

Error: Select: Keys "" passed to "selectedKeys" are not present in the collection.

Here's my code:

const PersonalInfo = () => {
  const [activeTab, setActiveTab] = useState("Basic Details");
  let basicDetailsObj: BasicDetailsType;

  let ProfileReq: ProfileType = {
    empid: "00004",
    profile: activeTab,
  };

  const handleGetProfile = () => {
    
    if(accessToken!=''){
      const user: LoginDetails = use(getUserDetailsByToken(accessToken));

      let ProfileReq: ProfileType = {
        empid: user.Empid,
        profile: activeTab,
      };

    const result: getprofile201Type = use(getProfile(accessToken,ProfileReq));
    //profile = result.getprofile201[0];
    switch (activeTab) {
      case "Basic Details":
        basicDetailsObj = result?.getprofile201[0];
        break;
      default:
        break;
        
    }
    }
  }

  const renderTabContent = () => {
    handleGetProfile()
    switch (activeTab) {
      case "Basic Details":
        return <BasicDetails 
        firstName= {basicDetailsObj?.firstName}
        lastName= {basicDetailsObj?.lastName}
        gender= {basicDetailsObj?.gender}
        />;
      default:
        return <BasicDetails 
        firstName= {basicDetailsObj?.firstName}
        lastName= {basicDetailsObj?.lastName}
        gender= {basicDetailsObj?.gender}
        />;
    }
  };

  return (
    <div className="mt-3 h-auto m-0 justify-center flex gap-3 flex-col">
      
      {renderTabContent()}
      
    </div>
  );
};

export default PersonalInfo;

Here's the BasicDetails Component:


import React from "react";
import Image from "next/image";
import { Button, Input, Select, SelectItem } from "@nextui-org/react";

interface IBasicDetails {
  firstName: string;
  lastName: string;
  gender: string;
}


const BasicDetails: React.FC<IBasicDetails> = ({
  firstName,
  lastName,
  gender
}) => {

  const [genderValue, setGenderValue] = React.useState(new Set([gender]));
  
  
  
  return (
    <div className="mb-5 h-full m-0 justify-center ">
      

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-5 text-gray-600">
        
        {/* First Name */}
        <div className="flex flex-col">
          <Input
            type="text"
            id="firstname"
            value={firstName}
            disabled
            isRequired
            label="First Name"
            placeholder=" "
            labelPlacement="outside"
          />
        </div>
        
        {/* Last Name */}
        <div className="flex flex-col">
          <Input
            type="text"
            id="lastname"
            value={lastName}
            disabled
            isRequired
            label="Last Name"
            placeholder=" "
            labelPlacement="outside"
          />
        </div>
        {/* Gender */}
        <div className="flex flex-col">
          <Select
            labelPlacement="outside"
            label="Gender"
            placeholder="Select Gender"
            selectedKeys={genderValue}
            className="max-w-lg text-black font-bold"
            isRequired
            fullWidth
          >
            <SelectItem key="Male" value="Male">
              Male
            </SelectItem>
            <SelectItem key="Female" value="Female">
              Female
            </SelectItem>
            <SelectItem key="Other" value="Other">
              Other
            </SelectItem>
          </Select>
        </div>
      </div>

    </div>
  );
};

export default BasicDetails;

I tried the documentations from NextUI and it doesn't work.

2

There are 2 answers

1
ichansaint On

Update: The reason of my error was passing an undefined or "" value on initial render that did not exist on the key of the

I already solved it by setting the default value of the field, and then I used useEffect to set the value from the parent component.

    
  const [genderValue, setGenderValue] = useState(["NOT SPECIFIED"]);

  useEffect(() => {
    setGenderValue([gender]);
  }, []);

The default value should exist in the key of

0
Montasir Mahmud On

It is just a warning, says the initial value you are passing using useState the value seems to be undefined of just an empty string "", which is not an option in select input. To solve this problem just add an prop defaultSelectedKeys="" when you are using multiple selection. Here is example:

<Select
          label="Courses"
          name="courses"
          placeholder="Choose Courses"
          className="w-full"
          selectionMode="multiple"
          defaultSelectedKeys="" // add this line
          selectedKeys={selectedCourses}
          onChange={handleSelectChange}
        >
          {semesterData.map((semester) => (
            <SelectItem
              key={semester.semester_code}
              value={semester.semester_code}
            >
              {semester.semester_name}
            </SelectItem>
          ))}
        </Select>