0

I'm building a web page that uses fetch to search information and it shows it to the user.

I've decided to store that information in a state but for some reason it doesn't work the way I expected.

When the data arrives I use setText() and then I print both the 'text' and 'data' variables.

Only 'data' is printing something, 'text' doesn't show anything.

Anyone knows what can be the problem here?

    const [text, setText] = useState("")

    const getTextFromApi = async () => {    
            
        const resp = await fetch(endpoint)
        const data = await resp.json()

        setText(data)
        console.log(data)
        console.log("------------------------")
        console.log(text)
    }
Jorge Sánchez
  • 27
  • 1
  • 1
  • 4
  • 1
    Does this answer your question? [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – Sysix Aug 19 '21 at 17:36

2 Answers2

1

In your example, setText is a function that queues another render of your function and updates the value that will be used for text in that and subsequent renders. It does not update the value of the text variable, which is a local variable.

Edit: this is explained in much more depth here: useState set method not reflecting change immediately

coreyward
  • 77,547
  • 20
  • 137
  • 166
1

Problem is that set state functions are asynchronous so you don't have the certainty that when you console log the value of the state it was already updated

you could do something like this inside your component

useEffect(() => {
   what you execute here will already have the text value set
},[text])
ManuC12
  • 33
  • 5