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?