Search code examples
reactjsreact-nativereact-hooksreact-native-navigationwix-react-native-navigation

State updating only after second onPress


I'm building a React Native app which renders a flatlist of groups. By pressing on one group, you get to see all the individual items nested within.

I'm using the following this navigation library and I'm passing props as such:

const navigateToDetails = useCallback(() => {
    Navigation.push(props.componentId, {
      component: {
        name: pagesNames.DETAILS,
        passProps: {
          groupId: selectedGroup,
        },
      },
    });
  });

All of this is within a functional component which has a couple more relevant things, to begin with we have the state and function that gets us selectedGroup:

const [selectedGroup, setSelectedGroup] = useState(Number);

function handleTouch(value) {
    setSelectedGroup(value);
    console.log('value: ' + value);
    navigateToDetails(value);
  }

value is taken from an item in a Flatlist which gets its data from this fake API.

Value is retrieved from the list in this fashion:

<FlatList
        data={data}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={[styles.card, { width: windowWidth - 30 }]}
            onPress={() => handleTouch(item.id)}>
           {misc components}
          </TouchableOpacity>
        )}
      />

Expected Behaviour

I'm expecting that when I tap an item from the list, it'd navigate to the Details page and populate it with its data. However this does not happen. Upon logging out value and selectedGroup, I find that value is always logged out correctly but selectedGroup is always first logged out as 0. Only after a second press does it show the expected id and populate the Details page.


Solution

  • You are redirected before state is set. initialize selectedGroup with null/undefined/0

    try navigating in useEffect

    function handleTouch(value) {
        setSelectedGroup(value);
        console.log('value: ' + value);
    }
    
    useEffect(() => {
      if (selectedGroup) {
       navigateToDetails(selectedGroup)
      }
    
    }, [selectedGroup, navigateToDetails])