Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda