Search code examples
typescriptapireact-hooksdropdownreact-typescript

Why Dropdown values not coming using typescript?


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]",

    }
]

Solution

  • 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:

    • Create some state in your component to store the response data, using useState
    • Start sending the request when your component first renders, with useEffect
    • When rendered with no state set, show some kind of loading message or spinner
    • When the response arrives (in your then callback) call setState with the response data - this will update the component's state and trigger a re-render
    • When the component renders and there is state available, then you can use it and show all your list items.