Search code examples
javascriptreactjsreact-nativereact-reduxreact-state-management

When I use onPress, I would like to set both these states at the same time


What I have noticed is that either one of these onPress functions works when used alone. But I want them both to happen together. How could I do it?

onPress={()=>setGroupSelected(item.groupName) setModalVisible(false)}

I want to use setGroupSelected and setModalVisible at the same time. The entire block of code that uses the above line is as follows

<FlatList    data={groups} 
             keyExtractor={item=>item.groupID.toString()}        
             renderItem={({item})=> <SelectionBoxComponent inputText={item.groupName} 
             onPress={()=>setGroupSelected(item.groupName) setModalVisible(false)}  > 
             </SelectionBoxComponent> }
                    />

Solution

  • One line arrow functions return the value indicated without a return statement.

    Try changing this (check the onPress function change)

    <FlatList    data={groups} 
                 keyExtractor={item=>item.groupID.toString()}        
                 renderItem={({item})=> <SelectionBoxComponent inputText={item.groupName} 
                 onPress={()=>setGroupSelected(item.groupName) setModalVisible(false)}  > 
                 </SelectionBoxComponent> }
                        />
    

    to this

    <FlatList    data={groups} 
                 keyExtractor={item=>item.groupID.toString()}        
                 renderItem={({item})=> <SelectionBoxComponent inputText={item.groupName} 
                 onPress={()=> {
                  setGroupSelected(item.groupName);
                  setModalVisible(false);
                 }}> 
                 </SelectionBoxComponent> }
                        />