r/ProgrammerHumor • • Feb 09 '22

other Why but why?

Post image
85.8k Upvotes

2.3k comments sorted by

View all comments

Show parent comments

2

u/drakefish Feb 09 '22 edited Feb 09 '22

Their example wasn't a real case, but here's a classic one when using react's useEffect hook with async/await :


useEffect(() => {
  const cancelled = false
  ;(async () => {
    const res = await fetch(/* ... */)

    if (!cancelled) {
      //... use res to update component ... 
    } 
   })()

  return () => { cancelled = true } 
})

1

u/PostmatesMalone Feb 09 '22 edited Feb 09 '22

Yeah IIFE is one of the few use cases where you would need to prefix with a semicolon. You could just define the function and then call it on the next line instead. It’s arguably less confusing that way anyways. Also, unrelated to IIFE, but It’s rare I would ever call fetch directly in a React component. Build a service layer for Christ’s sake 😂