TypeError: undefined is not an object (evaluating '_route$params.lat')

Viewed 522

I have react native app which I have two screens so in first screen the user will navigate to another screen where will get three values and in button clicked I am passing this values to the first screen again, in the second screen I am Passing parameters using something like this:

<TouchableOpacity style={styles.touch} onPress={() => this.props.navigation.navigate("dashboard", { lat: this.state.latitude, long:this.state.longitude, alt: this.state.altitude})}>

However I am getting this error TypeError: undefined is not an object (evaluating '_route$params.lat') in first screen which I understand that these values are null coz I have to navigate to the second screen and when navigate from second screen to first will pass these values. how I can fix that?

I have followed the documentation step by step also i did the following in first screen

const app = ({ route, navigation }) => {
    const { lat } = route.params;
    const { long } = route.params;
    const { alt } = route.params;

note that the second screen is class components and first screen is function components and the following is the stuck

    <RootStack.Navigator>
               //this first screen
                <RootStack.Screen
                    name="dashboard"
                    component={app}
                    options={{ headerShown: false }}
                />
//second screen
                <RootStack.Screen
                    name="location"
                    component={location}
                    options={{
    
                        title: 'Verify your location',
                    }}
                />
            </RootStack.Navigator>
1 Answers

What you are doing here is different than the normal passing of parameters. Here you are trying to pass parameters to the previous screen.

The error is showing because the first time when the screen is loaded there wont be any params so its undefined, but when you go to the next screen and pass parameters and navigate the params will be there. So the workaround you have to do is to validate the parameters.

You can do like below,which will set the value to lat if params are there.

const lat = route.params?.lat;

Also make sure that you check and use the value of lat as it would be undefined the first time.

You can check the documentation on passing params to previous screen here, useEffect hook can be used to check if the param is updated and act upon it. https://reactnavigation.org/docs/params/#passing-params-to-a-previous-screen

Related