Trying to bind data to dropdown, but not binding anything, dropdown displayes NOTHING SELECTED.
function Drop() {
axios.get('/api/v1/users/')
.then(function (response) {
global_num = response.data;
// console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
let lst = [];
for (let i in global_num) {
lst.push(global_num[i]['username']);
}
return (
<select style={{ width : "300px" , height: "40px", margin:"20px", fontSize:"18px"}} name="res">
{lst?.map((list) => (
<option value={list}> {list} </option>
))}
</select>
);
}
API result where username used for display as a dropdown options
Response from API:
[
{
"id": 1,
"username": "[email protected]",
}
]
React components render synchronously, which means that here your UI is rendered before you receive your HTTP response, and isn't updated when the response arrives later. That means your for (let i in global_num) { ...
code runs before the response arrives.
Instead, your component should:
useState
useEffect
then
callback) call setState
with the response data - this will update the component's state and trigger a re-render