Michael Burns
Michael Burns

Reputation: 19

setState inside a Promise function in a useEffect with hooks?

I'm trying to set the value of a hook inside a Promise function inside a useEffect() and being able to store the returned promise value in the fruit hook so I can access it in the return function of MyComponent()

This is what I tried so far:

const MyComponent = () => {
  const [fruit, setFruit] = useState('')

  useEffect(() => {
    // my promise function that returns a string (a random fruit)
    promiseFunction()
      .then(value => setFruit(value))
  }, [])

  return <div>fruit ? fruit : Loading...</div>
}

I have tried many approachs so far but none of them worked.

useEffect(() => {
  promiseFunction()
    .then(value => setFruit(() => value))
}, [])
useEffect(() => {
  promiseFunction()
    .then(value => setFruit((value) => { fruit = value }))
}, [])

After all that, the returned value of the hook is still empty.

There are no errors messages or anything, I tried debugging using another useEffect and it still returns an in the console.

How can I get the returned value of the promise function and store it in the fruit variable?

Upvotes: 0

Views: 1500

Answers (1)

josepholiveira
josepholiveira

Reputation: 743

The first code example looks perfect to me. My only concern is that the value is not being correctly returned from the function itself.

Have you tried to log the return from the promiseFunction? Another way to write this code would be to use a function that you can call inside the useEffect itself, like this:

useEffect(() => {
  async function loadFruitData() {
    const promiseFunctionReturn = await promiseFunction()
    
    console.log(promiseFunctionReturn)

    setFruit(promiseFunctionReturn)
  }
  
  //Call the function
  loadFruitData();
}, [])

This should give you a better way to see whats happening, and I also find it more readable.

But remember, if you're trying to console.log() the data right after the setFruit, it wouldn't show you the updated state, it happens because React has a queue that make the updates caused by the useState, that make it looks like an asynchronous update.

Upvotes: 3

Related Questions