Home > Net >  React - How to avoid assigning fallback value while loading?
React - How to avoid assigning fallback value while loading?

Time:07-14

I have a component that renders based on condition.

function MyComponent() {
  return <div>
   {isFruit ? 'Mango' : 'Onion'}
  </div>
}

The problem is that isFruit is fetched from an API, so it's undefined for some time.

While its undefined, the component renders with Onion (incorrectly), then updates with Mango when isFruit is fetched.

I want to defer the component render if isFruit value is undefined. Is there a way to do that? Or some other way to not show Onion during the API call.

CodePudding user response:

You could return an empty component if isFruit is undefined

function MyComponent() {
    if (isFruit === undefined) return <></>

    return <div>
    {isFruit ? 'Mango' : 'Onion'}
    </div>
}

CodePudding user response:

You can have a loading state to manage the wait time for api call. You will have to set loading to true when api call is triggered and set it back to false as soon as API call gets completed(failed or succeeded).This implementation can be handled like below:

function MyComponent() {
  const [loading,setLoading] = useState(true)
  useEffect(()=>{
    fetch(url).then((res)=>{
      //.... code here
      setLoading(false)
    }).catch((err)=>{
      //... err handling here
      setLoading(false)
    })
  },[])
  return <div>
  {
      loading ? <Loader /> : isFruit ? 'Mango' : 'Onion'
  }
  </div>
}
  • Related