'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source