Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

route.params not returning a variable with React Navigation

I'm attempting to pass a variable from one screen to another using React Navigation's route.params.

I've got this working on the screen immediately preceding it, but it's failing on the next screen and I cannot figure out why.

Here's the code:

      setTimeout(() => {
        console.log('here is the hid: ' + results.data.hid);
        navigation.navigate('MainHome', {
          hid: results.data.hid,
        });
      }, 2500);

The console log is correctly displaying the correct data in the console. This code leads to the next screen:

function Home({route, navigation}) {
  const hid = route.params;
  const [results, setResults] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');
  const [loading, setLoading] = useState('loading');

  console.log('Here is the hid that is retrieved from the route params on home:' + hid);

This console log is showing the hid as undefined.

Here is the expanded code for the referring screen:

function IntroOne({route, navigation}) {
  const [results, setResults] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');
  const [loading, setLoading] = useState('loading');

  const {email, password} = route.params;

  const CPRAPI = () => {
    api
      .get('create_account.php', {
        params: {
          email: email,
          password: password,
        },
      })
      .then(function (response) {
        // handle success
        setResults(response);
        setLoading('success');
      })
      .catch(function (error) {
        // handle error
        console.log('ERROR :(');
        console.log(error);
        setErrorMessage(error);
      });
  };

  useEffect(() => {
    CPRAPI();
  }, []);

  if (loading != 'success') {
    return (
      <View style={styles.container}>
        <Image
          style={{width: windowWidth, maxHeight: 250}}
          source={require('../components/parallel_universe.jpg')}
        />
        <ActivityIndicator size={'large'} color={'#ee1c24'} />
        <Text style={styles.header}>Loading...</Text>
      </View>
    );
  } else {
    if (results.data.intro_complete == 1) {
      setTimeout(() => {
        console.log('here is the hid: ' + results.data.hid);
        navigation.navigate('MainHome', {
          hid: results.data.hid,
        });
      }, 2500);

      return (
        <View style={styles.container}>
          <Image
            style={{width: windowWidth, maxHeight: 250}}
            source={require('../components/parallel_universe.jpg')}
          />
          <ActivityIndicator size={'large'} color={'#ee1c24'} />
          <Text style={styles.header}>Almost Done...</Text>
        </View>
      );
    }

Here is the expanded code for the receiving page:

function Home({route, navigation}) {
  const hid = route.params.hid;
  const [results, setResults] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');
  const [loading, setLoading] = useState('loading');

  console.log('Here is the hid that is retrieved from the route params on home:' + hid);

  const CPRAPI = () => {
    api
      .get('home.php', {
        params: {
          hid: hid,
        },
      })
      .then(function (response) {
        // handle success
        setResults(response);
        setLoading('success');
      })
      .catch(function (error) {
        // handle error
        console.log('ERROR :(');
        console.log(error);
        setErrorMessage(error);
      });
  };

  useEffect(() => {
    CPRAPI();
  }, []);

  if (loading == 'loading') {
    return (
      <View style={styles.container}>
        <Image
          style={{width: windowWidth, maxHeight: 250}}
          source={require('../components/parallel_universe.jpg')}
        />
        <ActivityIndicator size={'large'} color={'#ee1c24'} />
        <Text style={styles.header}>Loading...</Text>
      </View>
    );
  } else {
    return (
      <View>
        <Header
          placement="center"
          leftComponent={
            <View>
              <FontAwesomeIcon
                style={{margin: 9}}
                icon={['far', 'badge-dollar']}
              />
              <Text>{results.data.home_screen[0].firstname}</Text>
            </View>
          }
          centerComponent={{text: 'Hello, ', style: {color: '#fff'}}}
          rightComponent={
            <FontAwesomeIcon
              style={{margin: 9}}
              icon={['far', 'question-circle']}
            />
          }
        />
        <ScrollView>
          <View style={styles.container}>
            <Image
              style={{width: windowWidth, maxHeight: windowHeight / 5}}
              source={require('../components/parallel_universe.jpg')}
            />
            <Text style={styles.header}>Hello, {}</Text>
            <Text style={styles.textSmaller} />
            <Text style={styles.textMuchSmaller}>
              We will never spam you or sell your email.
            </Text>
          </View>
        </ScrollView>
      </View>
    );
  }
}

Here are my stacks:

const GettingStartedStack = createStackNavigator();

function GettingStartedScreen() {
  return (
    <GettingStartedStack.Navigator>
      <GettingStartedStack.Screen
        name="Getting Started"
        component={GettingStarted}
        options={{headerShown: false}}
      />
      <GettingStartedStack.Screen
        name="Question One"
        component={gs1}
        options={{title: 'Your Shadow Self'}}
      />
      <GettingStartedStack.Screen
        name="Defining Moment Narrative"
        component={gs1entry}
      />
      <GettingStartedStack.Screen
        name="Question Two"
        component={gs2}
        options={{title: 'Credits & Money'}}
      />
      <GettingStartedStack.Screen
        name="Define Myself"
        component={gs2entry}
        options={{title: 'College'}}
      />
      <GettingStartedStack.Screen
        name="Concentration"
        component={gs2Aentry}
        options={{title: 'Concentration'}}
      />
      <GettingStartedStack.Screen
        name="Homeland"
        component={gs3}
        options={{title: 'Your Homeland'}}
      />
      <GettingStartedStack.Screen
        name="Choose Homeland"
        component={gs3entry}
        options={{title: 'Choose Your Homeland'}}
      />
      <GettingStartedStack.Screen
        name="Citizenship"
        component={gs4}
        options={{title: 'Your Citizenship'}}
      />
      <GettingStartedStack.Screen
        name="Choose Citizenship"
        component={gs4entry}
        options={{title: 'Choose Your Citizenship'}}
      />
      <GettingStartedStack.Screen name="Banking" component={gs5} />
      <GettingStartedStack.Screen
        name="Choose Banking"
        component={gs5entry}
        options={{title: 'Choose Your Bank'}}
      />
      <GettingStartedStack.Screen
        name="Luck"
        component={gs6}
        options={{title: 'Are You Feeling Lucky?'}}
      />
      <GettingStartedStack.Screen name="Parents" component={gs7} />
      <GettingStartedStack.Screen name="Siblings" component={gs8} />
      <GettingStartedStack.Screen name="Inheritance" component={gs9} />
      <GettingStartedStack.Screen name="More Credits" component={moreCredits} />
    </GettingStartedStack.Navigator>
  );
}

const IntroStack = createStackNavigator();

function IntroStackScreen() {
  return (
    <IntroStack.Navigator>
      <IntroStack.Screen
        name="Welcome"
        component={IntroOne}
        options={{headerShown: false}}
      />
      <IntroStack.Screen
        name="Empire Universe"
        component={IntroTwo}
        options={{headerShown: false}}
      />
      <IntroStack.Screen
        name="Shadow Self"
        component={IntroThree}
        options={{headerShown: false}}
      />
    </IntroStack.Navigator>
  );
}

const HomeStack = createStackNavigator();

function HomeStackScreen() {
  return (
    <HomeStack.Navigator>
      <HomeStack.Screen
        name="Home"
        component={Home}
        options={{headerShown: false}}
      />
    </HomeStack.Navigator>
  );
}

const FinancesStack = createStackNavigator();

function FinancesStackScreen() {
  return (
    <FinancesStack.Navigator>
      <FinancesStack.Screen
        name="Finances"
        component={Finances}
        options={{headerShown: false}}
      />
    </FinancesStack.Navigator>
  );
}

const Tab = createBottomTabNavigator();

function MainTabs() {
  return (
    <Tab.Navigator
      screenOptions={({route}) => ({
        tabBarIcon: ({focused, color, size}) => {
          let iconName;

          if (route.name === 'Cyclopedia') {
            iconName = focused ? 'books' : 'books';
          } else if (route.name === 'Big Think') {
            iconName = focused ? 'head-side-brain' : 'head-side-brain';
          } else if (route.name === 'Getting Started') {
            iconName = focused ? 'key-skeleton' : 'key-skeleton';
          } else if (route.name === 'CSX') {
            iconName = focused ? 'chart-area' : 'chart-area';
          } else if (route.name === 'Marketwire') {
            iconName = focused ? 'analytics' : 'analytics';
          } else if (route.name === 'Login') {
            iconName = focused ? 'user-cog' : 'user-cog';
          } else if (route.name === 'Map') {
            iconName = focused ? 'map' : 'map';
          } else if (route.name === 'Intro') {
            iconName = focused ? 'home' : 'home';
          } else {
            iconName = focused ? 'books' : 'books';
          }

          // You can return any component that you like here!
          return <FontAwesomeIcon icon={['far', iconName]} />;
        },
      })}
      tabBarOptions={{
        activeTintColor: 'tomato',
        inactiveTintColor: 'gray',
      }}>
      <Tab.Screen name="Home" component={HomeStackScreen} />
      <Tab.Screen name="Finances" component={FinancesStackScreen} />
    </Tab.Navigator>
  );
}

const MainStack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <MainStack.Navigator>
        <MainStack.Screen
          name="Welcome"
          component={IntroStackScreen}
          options={{headerShown: false}}
        />
        <MainStack.Screen
          name="MainHome"
          component={MainTabs}
          options={{headerShown: false}}
        />
        <MainStack.Screen
          name="Getting Started"
          component={GettingStartedScreen}
          options={{headerShown: false}}
        />
      </MainStack.Navigator>
    </NavigationContainer>
  );
}

Any thoughts about what could be causing this? I've tried a bunch of things, but just can't seem to get it to resolve properly.

I'm using:

React Native - 0.63.4 "@react-navigation/bottom-tabs": "^5.11.7", "@react-navigation/native": "^5.9.2", "@react-navigation/stack": "^5.14.1",

Thanks in advance!

like image 447
Richard Baldwin Avatar asked Dec 12 '25 03:12

Richard Baldwin


1 Answers

In react-navigation 5 ... we need to specify what screen you wanna navigate to in case of nested-navigators...

Try this:

navigate('MainHome', {
  screen: Home,
  params: {
    screen: 'Home',
    params: {
      hid: results.data.hid,
    },
  },
});
like image 128
Hend El-Sahli Avatar answered Dec 15 '25 23:12

Hend El-Sahli



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!