Search code examples
javascripttypescriptreact-nativeroutesreact-navigation-stack

How to send data from multiple screen to one single screen in React native


i have basically four screens and i am sending the data to other screen. for example i am sending the data from Home to ListScreen with some items from flatlist then i am also sending the other data from SearchScreen to ListScreen but problem here in when i go to ListScreen from TabScreen or then it gives me error on {item.name}

 <TouchableOpacity onPress={() => navigation.navigate(MainScreens.ListScreen, {
                     item: item, 
                     })} >
                       
                </TouchableOpacity>

and there also

<TouchableOpacity onPress={() => navigation.navigate(MainScreens.ListScreen, {
                     item: item, 
                     totalFixed: totalPrice,
                     })} >
                       
                </TouchableOpacity>

my question is how can i differentiate them in ListScreen how can i came to know that these both data are different from each other

export const ListScreen: React.FC<ListScreenProps> = ({ route, navigation }) => {
    const { item, totalFixed } = route.params || {};

here i have two types of object in item item.name and item.category but i get error below here i have error that item.price not found because i came with home screen.

 <Text >Total: AED {item.price}</Text>

Solution

  • <TouchableOpacity onPress={() => navigation.navigate(MainScreens.ListScreen, {
                         item: item, 
                         source:'home'
                         })} >
                    </TouchableOpacity>
    

    add source here as well so you can remember the screen data

    <TouchableOpacity onPress={() => navigation.navigate(MainScreens.ListScreen, {
                             item: item, 
                             source:'searchScreen'
                             })} >
                        </TouchableOpacity>
    

    and then get the data like this in ListScreen

    export const ListScreen: React.FC<ListScreenProps> = ({ route, navigation }) => {
    const { item, totalFixed, source } = route.params || {};
    

    now add your text in ListScreen something like this

    {source === 'home' && (
                            < Text>Total: AED {item.price}</Text >)}
                        {source === 'searchScreen' && (
                            <Text>Total: AED {totalFixed}</Text>)}