1

I know an async/await function only returns a promise, and that I need to add a .then() to update a variable or a state with the value. But in a React app, it obliges me to perform a useEffect and then to update a state. If I return a formatted object such as: {loading, error, data}, would it be possible to directly access it this way:

const {loading, error, data} = fetchData()

How would you allow direct access to an object from such a function:

async function foo(){
try{
const res = await api("/user/foo")
return {
  loading:false,
  error:false,
  data: res.data
  }
 }
 catch{
 return trhow new Error()
 }
 }
DoneDeal0
  • 5,273
  • 13
  • 55
  • 114
  • 1
    No. You need to await it or use then. – jonrsharpe Dec 25 '20 at 22:29
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jmargolisvt Dec 25 '20 at 22:31
  • I can't await outside an async function. If I have to use a then, what would be a clean/nice way to handle it outside of my component so I can directly call for the result and destructure it? – DoneDeal0 Dec 25 '20 at 22:31

2 Answers2

0

if what you want is to get an object back from an async function then that is not possible without using "await" or ".then" so your best option is to store the returned value from the async function in a state and using the formatted object passed to that state. if you want to use it in an useEffect handler it's not possible as react would throw warnings or errors, to bypass this is to use useCallback and then pass the useCallback to the useEffect handler.

I hope this answer's your question

classic-code
  • 136
  • 1
  • 3
0

when dealing with useEffect and a some promise function foo that you have to wait you can deal with the following approaches:

async/await approach, declare a function baz then call it:

useEffect(() => {
  async function baz() {
    try {
      const res = await foo()
      // do something with res
    } catch (error) {
      console.log(error)
    }
  }
  
  await baz()
}, [])

chaining promise:

useEffect(() => {
  baz()
    .then(res => {
       // do something with res
     })
    .catch(console.log)
}, [])
buzatto
  • 9,704
  • 5
  • 24
  • 33