0

My Functional component is as follows:

const Scratch = () => {

 const [isLoaded, setIsLoaded] = useState(false);
 const colorSelectItems=[];
 const [selectedColor, setSelectedColor] = useState("fffff");

 useEffect(() => {
    fetch(
           `http://localhost:8765/fetchData?userId=1`
         )
      .then((response) => response.json())
      .then((data) => {
       createDropDown(data));
       setIsLoaded(true);
      });
  }, []);

 const createDropDown= (data) => {
    data.map((color) => {
      colorSelectItems.push({
        label: color.colorName,
        value: color.hexValue,
      });
    });

 return (
     <div className="commonMargin">
         {!isLoaded&& <p>Loading..</p>}
         {isLoaded&& (
           <Dropdown
            value={selectedColor}
            optionLabel="label"
            options={colorSelectItems}
            onChange={(e) => setSelectedColor(e.target.value);}
           />
          )}
     </div>
  );
};

export default Scratch;

The problem is, it is displaying Loading... until the API call is complete, and it is rendering DropDown after that. But even after the completion of API call, the DropDown is still empty!

What am I missing here?

PS: This DropDown works perfectly if I replace fetching data from API to fetching data from local json file

Harihara_K
  • 174
  • 16

1 Answers1

2

Try this .In case any problem plz reply

const Scratch = () => {

 const [isLoaded, setIsLoaded] = useState(false);
 const colorSelectItems=[];
 const [selectedColor, setSelectedColor] = useState("fffff");

 useEffect(() => {
    fetch(
           `http://localhost:8765/fetchData?userId=1`
         )
      .then((response) => response.json())
      .then((data) => {
       var temp=data?.map((item)=>({label: item?.colorName,
        value: item?.hexValue }));
       colorSelectItems=temp;
       setIsLoaded(true);
      });
  }, []);
     
 return (
     <div className="commonMargin">
         {!isLoaded&& <p>Loading..</p>}
         {isLoaded&& (
           <Dropdown
            value={selectedColor}
            optionLabel="label"
            options={colorSelectItems}
            onChange={(e) => setSelectedColor(e.target.value);}
           />
          )}
     </div>
  );
};

export default Scratch;
  • Yeah, I had solved the issue in the similar way; with one change. `const [colorSelectItems,setColorSelectItems]=useState([]);` and then instead of `colorSelectItems=temp;` ,I used `setColorSelectItems(temp)` . – Harihara_K Mar 02 '21 at 16:27
  • @Harihara_K ok bro, thanks for the reply and support –  Mar 03 '21 at 03:32