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

104
Visualizações
useState weird update

I have this function that get some data and put in a array, and, in the end, change de value of the test useState to the content of that array

const [teste, setTeste] = useState('DefaultValue');
const fetchTeses = () => {
      const textTeses = [];
      fetch('http://localhost:8000/teses')
      .then(res => {
          if(!res.ok){
              throw Error('Could not fetch the data for that resource')
          }
          return res.json()
      })
      .then((data) => {
        items.forEach((element, index) => {
          tesesEscolhidas.forEach((teseEscolhida) => {
            if(element.indexOf(teseEscolhida)!=-1){
              textTeses.push(data[index]['Content']);
            }
          })
        })
      }).then((data) => {
        setTeste(textTeses)
      })
    }

This function is called by clicking on a button:

<Button color="secondary" size="large" variant="contained" onClick={fetchTeses}>Resetar</Button>

But I call the test useState in another function, which is called by clicking in another button:

<Button color="primary" size="large" variant="contained" onClick={generateFromUrl}>Criar arquivo docx</Button>

The second function:

    const generateFromUrl = async() => {
      const blob = await fetch(
        "https://raw.githubusercontent.com/dolanmiu/docx/master/demo/images/cat.jpg"
      ).then(r => r.blob());
  
      const doc = new Document({
        sections: [
          {
            children: [
              new Paragraph(teste[0])
            ]
          }
        ]
      });
  
      Packer.toBlob(doc).then(blob => {
        console.log(blob);
        saveAs(blob, nameFile+".docx");
        console.log("Document created successfully");
      });
    }

But the weird part is that when I call the test useState in the second function he pass the DefaultValue, even though I have already executed the first function and already assigned the new value to the test useState. (I notice that if I execute the first function more than once, the new value is finally assigned)

However, when I create an element with test useState value and do the exaclty same thing, the value passed in the second function is the new value assigned in the first function, which is what i want to happen.

Example:

<TextField id="nameTest" label="Teste" variant="outlined" color="primary" fullWidth helperText="Teste" value={teste ? teste : ''} />

Why is this happening and how to avoid this?

I know this has to do with the render thing, but I really can't figured out how to made this works.

about 4 years ago · Juan Pablo Isaza
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