BobSacamano
BobSacamano

Reputation: 157

Should I call a function that returns a promise immediately after setState or in the dependency array of useEffect()

My code (which seems to work ok) looks like this:

import { SplashScreen } from "@capacitor/splash-screen";

const MyComponent = () => {
  const [data, setData] = useState()

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    const response = await fetch("some_api")
    setData(response.data)
    await SplashScreen.hide()
  } 

  return (<div>{JSON.stringify(data)}<div>)
}

But I'm wondering if it's better practive to move the await SplashScreen.hide() function call to a useEffect() with the data in the dependency array like this:

import { SplashScreen } from "@capacitor/splash-screen";

const MyComponent = () => {
  const [data, setData] = useState()

  useEffect(() => {
    init()
  }, [])

  useEffect(() => {
    if (data) {
      await SplashScreen.hide()
    }
  }, [data])

  const init = async () => {
    const response = await fetch("some_api")
    setData(response.data)
  } 

  return (<div>{JSON.stringify(data)}<div>)
}

Note: SplashScreen.hide() returns a promise. Which way is better and why?

Upvotes: 1

Views: 35

Answers (1)

Clarity
Clarity

Reputation: 10873

It depends if you want to call SplashScreen.hide() after the data has been set or not. In the first case it's not guaranteed that the call will be made after the data is set since setState works async. In the second case though, you are explicitly calling SplashScreen.hide() after the state has been updated.

Note, since you're not doing anything with the promise returned from SplashScreen.hide(), it's not necessary to call it with await.

Upvotes: 1

Related Questions