Home > Back-end >  How can I wait for all the hooks to finish loading before rendering the component?
How can I wait for all the hooks to finish loading before rendering the component?

Time:10-11

I have a component that has many hooks, for example:

import useProfilePermission from 'hooks/useProfilePermission'



  const { a } = useProfilePermission(1)
  const { b } = useProfilePermission(2)
  const { c } = useProfilePermission(3)
  const { d } = useProfilePermission(4)

Later I use these variables a, b, c, d and do some conditional rendering

The useProfilePermission makes a network request so It takes some time to load, How do I wait for variables to completely load before the get to the return statement for that functional component?

CodePudding user response:

You can use conditional rendering here. The condition would be that all of the constants resulting from the request are not null or not undefined (e.g.you could cast to a boolean by using the double exclamation mark), or that they are equal to a certain string (e.g. a.status === 'ok').

const App = () => {
  const a = usePermission(1_000)
  const b = usePermission(2_000)
  const c = usePermission(3_000)

  return (
    !!a && !!b && !!c 
        ? <p>got permission</p>
        : <p>loading....</p> // or null
    
  )
}

/* or like this : */

const App = () => {
  const a = usePermission(1_000)
  const b = usePermission(2_000)
  const c = usePermission(3_000)

  return (
    a.status === 'ok' && b.status === 'ok' && c.status === 'ok' 
        ? <p>got permission</p>
        : <p>loading....</p> // or null
    
  )
}

Here a working simplified version : link

CodePudding user response:

Assuming that the permissions (a, b, c, d) are undefined or null until the api ends, you can return null (or a spinner) from the component:

const { a } = useProfilePermission(1)
const { b } = useProfilePermission(2)
const { c } = useProfilePermission(3)
const { d } = useProfilePermission(4)

if(!a || !b || !c || !d) return null

CodePudding user response:

Combination of useEffect and useState.

...
function App(){
    const [isLoading, setIsLoading] = useState(true);
    const { a } = useProfilePermission(1);
    const { b } = useProfilePermission(2);
    const { c } = useProfilePermission(3);
    const { d } = useProfilePermission(4);
    useEffect(() => {
        if (a && b && c && d) setIsLoading(false)
    }, [a, b, c, d]);
    if (isLoading) return null; // skip the render
    return <view>...</view>
}

CodePudding user response:

You can return state(isLoading) from useProfilePermission() and use it.

const {a , isLoading} = useProfilePermission(1)

if(isLoading) showLoading()...

  • Related