reactjsrenderingdropdown

Information from API Call not getting rendered in ReactJS dropdown option


I have a Drop Down with Code:

<select
                  name="AssetCategory"
                  value={formData.AssetCategory}
                  onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>
                    setFormData((prev) => ({
                      ...prev,
                      AssetCategory: Number(e.target.value),
                    }))
                  }
                  className="w-full border border-teal-500 p-2 rounded-lg"
                >
                  <option value="">Select a Category</option>
                  {Array.isArray(CategoryData) &&
                    CategoryData.map((category) => (
                      <option key={category.catID} value={category.catID}>
                        {category.catName}
                      </option>
                      
                    ))}
                    <option>Nothing</option>
                </select>

This is how I have fetched the AssetCategory:

 const fetchCategories = async () => {
    try {
      const { data }: { data: TypeCatgRes } = await api.get("/AssetCategory");
      setCategoryData(data.results || data);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

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

But Asset Category Name is not getting rendered. Asset Catogory Drop Down Screen

This is what the API Get Request in Postman for AssetCategory looks like: Asset Category Get


Solution

  • Your fetchCategories function is handling response like this,

    setCategoryData(data.results || data);
    

    But in your Postman screenshot, the API is returning a single Objecty directly.

    {
      "catID": 2,
      "catName": "Sofa"
    }
    

    Since this is a single Object, not an array, when you try to map over it in your dropdown, nothing renders. Because Array.isArray(CategoryData) is getting false

    Update your fetchCategories function to handle both single Object and Arrays

    const fetchCategories = async () => {
      try {
        const { data }: { data: TypeCatgRes } = await api.get("/AssetCategory");
        
        // Check if data is an array or a single object
        if (Array.isArray(data)) {
          setCategoryData(data);
        } else if (data.results && Array.isArray(data.results)) {
          setCategoryData(data.results);
        } else (data && data.catID) {
          // If it's a single object, wrap it in an array
          setCategoryData([data]);
        }
      } catch (error) {
        console.error("Error fetching categories:", error);
      }
    };