Reputation: 164
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
Upvotes: 0
Views: 904
Reputation:
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;
Upvotes: 2