react native navigation useFocusEffect triggered before goBack

Viewed 85

I use react-native-navigation and redux. I have a Stack Navigator with two screens.

The second screen uses some data stored in redux by the first screen. The first screen has a function that resets that data inside a useFocusEffect hook so when the focus is back on the first screen all the data will be erased.

// First Screen

useFocusEffect(
   useCallback(() => {
      dispatch(clearAllData());
    }, []);
);

The problem is that if I try to go back to the first screen using navigation.goBack() somehow the data is cleared before the second screen is completely unmounted and it throw an error.

// Second Screen
const some_params = useSelector(state => state.data.some_params);

// error: can't read property "some_params" of null

I tried adding a little timeout on the dispatch(clearAllData()) and it worked but I don't think it's a valid solution.

I can use the optional chaining like state?.data?.some_params but I will have to use it everywhere.

Is it possible to trigger clearAllData being sure the second screen is completely unmounted?

Edit

I've tried both useIsFocused and navigation.pop() but none of them works as expected.

Finally I found a solution using InteractionManager.runAfterInteractions

useFocusEffect(
  useCallback(() => {

    const task = InteractionManager.runAfterInteractions(() => {
      dispatch(clearAllData());
    });

    return () => task.cancel();

  }, [])
);
1 Answers

Can you try clearing data like this

import { useIsFocused } from '@react-navigation/native';

const focused = useIsFocused()

    useEffect(()=>{
        if(focused){
            dispatch(clearAllData());
        }
    },[focused])

Related