Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, wait for a hook to finish before starting another hook

I have a component like follows

export const Component = () => {
  const { data: item} = useItem();
  const { list } = useItemList(item?.id.toString());


  return(
    item ? (<p>some stuff</p>) : (<p>loading</p>)
  )
}

Problem is the app is not waiting for item to be available and it runs useItemList while its undefined, but i’ve to wait to fetch item

How can I solve so?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you cannot run the hook conditionally because React relies on the order in which Hooks are called

React cannot track the state correctly if a hook is skipped

An easy solution is to modify your useItemList code, if the argument is undefined, then don’t call whatever is inside it.

update: my solution is incorrect because the hook value is initial value, so it wont work.

this is the correct solution:

You should return a memorized callback from useItemList instead and run this callback in useEffect with item and that callback(optional) as dependency

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading