Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
React select dropdown not updating on fetch

I'm having this problem with React where I'm trying to render a select dropdown with dates stored in my database. The data is fetched succesfully and the states are updated as well, it can be console logged. However the select dropdown is not being rendered as it should:


 function Home(){
  const [userdata, setUserdata] = useState();
  const [historyLogs, setHistoryLogs] = useState();

  useEffect(() => {
    async function firstRun(){ 
      var userdata = await (await fetch("/me")).json();
      var historyLogs = []
      firebase.database().ref(userdata.id).once("value", function(snapshot){
        snapshot.forEach(child => {
          historyLogs.push(child.key);
      })});

      setHistoryLogs(historyLogs);
      setUserdata(userdata);
    }
    firstRun();
  }, [])

  function aver(){
    console.log(historyLogs);
  }

  if(!userdata || !historyLogs){
    return null
  }
  else{

    return (
      <React.Fragment>
        <button onClick={aver}>aver</button>
        <header>
              <img src={logo} height="50px" alt="logo"/>

              <select id="cars" name="carlist" form="carform">
                  <option value="volvo" selected>volvo</option>
                  {
                  historyLogs.map(log => {
                      return <option>{log}</option>
                    })
                  }
              </select>

              <div className="user-info">
                  <img src={userdata.img} height="50px" style={{borderRadius:"50%"}} alt="user img"/>
                  <p>{userdata.name}</p>
              </div>
        </header>
        <Toptracks userdata={userdata}/>
      </React.Fragment>
    )
  }

}

export default Home;

With the code I have, the dropdown renders without rendering the historyLogs list, so it only shows this: enter image description here

and this should be displayed inside (console logged):

(2) ["2021-7-25", "2022-7-25"]

I interesently found out that if I make any change in the code with my local server running, it gets updated as it should be on the first place:

enter image description here

Any help is very much appreciated :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The solution has been thanks to @click2install and @NickServe on Reactiflux Discord server:

Your once code is in an asyncronous event listener, which means it's running after you set your state to [ ]. You should call setHistoryLogs inside of once instead.

Final solution:

useEffect(() => {
    async function firstRun(){ 
      var userdata = await (await fetch("/me")).json();

      firebase.database().ref(userdata.id).once("value", 
        function(snapshot){
          var historyLogs = []
          snapshot.forEach(child => {
            historyLogs.push(child.key)
          });
          setHistoryLogs(historyLogs);
        }
      );

      setUserdata(userdata);
    }
    firstRun();
  }, [])
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda