Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native navigation.navigate params not updating

I try to navigate from home screen to detail screen using navigation.navigate(). When the first time i click button to navigate it works fine, but after that when i go back from detail to home and click another item to see the detail, the params on detail screen is not changed (its still the params of the 1st click). Here my code :

<TouchableNativeFeedback
  key={index}
  onPress={() => {
    navigation.navigate('PenghuniScreen', {
      screen: 'DetailPenghuni',
      params: {
        penghuni: item,
      },
    });
  }}></TouchableNativeFeedback>;

item is object from map loop . i try to console log using react navigation usefocuseffect and the params not changin after 1st click.

useFocusEffect(
    React.useCallback(() => {
      console.log('My params:', route.params.penghuni);
      setPenghuni(route.params.penghuni);
      return () => {
        // source.cancel('Api Canceled');
        console.log('tutup detail penghuni');
      };
    }, []),
  );

anyone got solution for this?

like image 859
imamseptian Avatar asked Jun 28 '26 13:06

imamseptian


1 Answers

You forgot to add the route dependency to your useCallback, so it is getting the old value.

Try adding [route]:

React.useCallback(() => {
      console.log('My params:', route.params.penghuni);
      setPenghuni(route.params.penghuni);
      return () => {
        // source.cancel('Api Canceled');
        console.log('tutup detail penghuni');
      };
}, [route]), 

I suggest you adding the eslint for hooks to your project, to detect missing dependecies. exhaustive-deps warning

Observation: Why don't you pass these values though the navigation params instead of using useFocusEffect?

navigation.navigate('DetailPenghuni', { penghuni: item1 }) // item1 press 
navigation.navigate('DetailPenghuni', { penghuni: item2 }) // item2 press

If you need to cancel something you can always use the useEffect clean callback called automatically when you close a screen.

like image 78
Roni Castro Avatar answered Jun 30 '26 02:06

Roni Castro



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!