skip to Main Content

here is the code on AddCourse.tsx. i want to show the instructors name from API. it’s run fine on console log but it didn’t show up in dropdown options

const [instructorOptions, setInstructorOptions] = useState<
    Array<{ id: string; value: string; label: string }>
  >([]);

const fetchOptions = async () => {
    try {
      const response = await axios.get(`${API_URL}/instructor`);
      const instructorList: Array<{ id: string; name: string }> =
        response.data.data.instructor_list;

      if (instructorList.length > 0) {
        const options = instructorList.map((instructor) => ({
          id: instructor.id,
          value: instructor.name,
          label: instructor.name,
        }));
        setInstructorOptions(options);
        console.log('options : ', options);
      }
    } catch (error) {
      console.error('Error fetching instructors:', error);
      // Handle error, set appropriate state if needed
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOptions();
  }, []);

  const handleSelect = (selectedOption: any) => {
    // Lakukan sesuatu dengan opsi yang dipilih, misalnya simpan di state
    console.log('Opsi yang dipilih:', selectedOption);
  };
<div className="input-instructor">
  <InputDropDown
     options={instructorOptions}
     handleSelect={handleSelect}
  />
</div>

this is the InputDropDown component:

import React, { useState } from 'react';
import Select from 'react-select';
import { BsTrash3 } from 'react-icons/bs';

function InputDropDown({ options, onSelect, text }: any) {
  const [optionsAvailable, setOptionsAvailable] = useState<string[]>(options);
  const [option, setOption] = useState<string[]>([]);
  const [selectedOption, setSelectedOption] = useState('');

  const handleSelectChange = (selectedOption: any) => {
    if (selectedOption && !option.includes(selectedOption)) {
      setOption((prevOptions) => [...prevOptions, selectedOption]);

      const updatedOptions = optionsAvailable.filter(
        (option: any) => option !== selectedOption,
      );

      setOptionsAvailable(updatedOptions);
    }
    setSelectedOption('');
  };

  const handleOptionRemove = (optionId: any) => {
    const updatedoptions = option.filter((item: any) => item.id !== optionId);
    console.log(updatedoptions);
    setOption(updatedoptions);

    //update options available
    const deletedOptions = options.filter((item: any) => item.id === optionId);
    setOptionsAvailable((prevOptions) => {
      const newOptions = [...prevOptions, ...deletedOptions];
      // Sort the newOptions array by id in ascending order
      newOptions.sort((a, b) => a.id - b.id);
      return newOptions;
    });
  };

  return (
    <>
      <label className="mt-3 mb-3 block text-black dark:text-white">
        {text}
      </label>
      <Select
        value={selectedOption}
        onChange={handleSelectChange}
        options={optionsAvailable}
        isSearchable={true} // Aktifkan fitur pencarian
        placeholder="Pilih salah satu..."
      />
      <br />
      {option.map((data: any) => (
        <div className="flex mt-3 flex-row gap-2" key={data.id}>
          <div className="bg-primary text-white rounded-md px-2 py-1">
            {data.value}
          </div>
          <button
            onClick={() => handleOptionRemove(data.id)}
            className="bg-[#EF4444] text-white rounded-md px-2 py-1"
          >
            <BsTrash3 />
          </button>
        </div>
      ))}
    </>
  );
}

export default InputDropDown;

options do not appear even though in console.log options appear
enter image description here

how to make my code can show the instructors name in the options?

3

Answers


  1. Can you please share InputDropDown component code? It is from any library(e.g. MUI, ANTD, etc) or Is it the custom dropdown component?

    Login or Signup to reply.
  2. you need to make sure that the instructorOptions state is properly updated after fetching the instructors from the API. The fetchOptions function seems to be correct, the InputDropDown component might not be re-rendering when the instructorOptions state changes.

    I have updated the code snippet try this:

    const [instructorOptions, setInstructorOptions] = useState<
      Array<{ id: string; value: string; label: string }>
    >([]);
    
    const fetchOptions = async () => {
      try {
        const response = await axios.get(`${API_URL}/instructor`);
        const instructorList: Array<{ id: string; name: string }> =
          response.data.data.instructor_list;
    
        if (instructorList.length > 0) {
          const options = instructorList.map((instructor) => ({
            id: instructor.id,
            value: instructor.name,
            label: instructor.name,
          }));
          setInstructorOptions(options);
          console.log('options : ', options);
        }
      } catch (error) {
        console.error('Error fetching instructors:', error);
      } finally {
        setLoading(false);
      }
    };
    
    useEffect(() => {
      fetchOptions();
    }, [instructorOptions]);
    
    const handleSelect = (selectedOption: any) => {
      console.log('Opsi yang dipilih:', selectedOption);
    };
    
    <div className="input-instructor">
      <InputDropDown
        options={instructorOptions}
        handleSelect={handleSelect}
      />
    </div>
    
    Login or Signup to reply.
  3. You can try this hope this will solve the problem :

    <div className="input-instructor">
    {instructorOptions && (
    <InputDropDown
    options={instructorOptions}
    handleSelect={handleSelect}
    />
    )}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search