Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

willFocus event in react navigation 5

I need to fetch data before focus event. I saw that there was an willFocus event in react navigation 4 but it seems that the event was removed in react navigation 5.
componentDidMount cannot do the trick because I want to fetch data as soon as possible even before the screen comes into focus each time the user navigate to my screen.

like image 714
Jules Avatar asked Apr 07 '26 15:04

Jules


2 Answers

You CANNOT fetch data before componentDidMount. That's literally the first thing happens when a new screen is rendered.

Regarding fetching data each time when the screen is focused, you need to use focus event as mentioned in the migration guide: https://reactnavigation.org/docs/upgrading-from-4.x/#navigation-events

The focus event equivalent to willFocus from before. It fires as soon as the screen is focused, before the animation finishes. I'm not sure what you mean by it fires too late.

Also, for data fetching, there is a special hook: useFocusEffect

https://reactnavigation.org/docs/use-focus-effect/

like image 172
satya164 Avatar answered Apr 10 '26 03:04

satya164


You could do something like:

  /**
   * Your redux action should set loading-state to false after
   * fetch-operation is done...
   */
  reduxActionDoingFetch();

  useEffect(() => {
    if (reduxActionDoingFetch_Loading === false) {
      Navigation.navigate('YourTargetScreen');
    }
  }, [reduxActionDoingFetch_Loading]);
like image 43
Hend El-Sahli Avatar answered Apr 10 '26 03:04

Hend El-Sahli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!