Home > Mobile >  How to Pass params to a route by putting them in an object
How to Pass params to a route by putting them in an object

Time:02-18

I try to send data to another page with passing parameter, from page1 to page2.

this is my code from page1 :

axios({
            method: 'post',
            url: "http://127.0.0.1:8000/api/masuk",
            data: {
                username: {username}
            }
        })
            .then(function (response){
                if (response.data.data != null) {
                    // Alert.alert(`Username ${username} tidak terdaftar`);
                    console.log(response.data)
                    setdataPetugas(response.data)
                    navigation.navigate('Home', {test: 'name'});
                } else {
                    console.log(response.data)
                    Alert.alert(`Username ${username} tidak terdaftar`);
                    setLoading(false);
                }
            })
            .catch(function (error){
                console.log(error)
            });

and this is code from page2 :

const Page = ({route, navigation}) => {
const {test} = route.params;
console.log(test);
return (
    <SafeAreaView style={{ backgroundColor: 'white', }}>
        <ScrollView style={{ paddingHorizontal: '5%' }}>
            <Texts text="Hi, Asep" color="grey" />
            <Gap vertical="5%" />
            <View style={{ flexDirection: 'row' }}>
                <View style={{flex:.8,alignItems:'center'}}>
                    <Image source={require('../../../assets/images/user-profile.png')} resizeMode="cover" style={{ width: 60, height: 60, borderRadius: 10 }} />
                </View>
                <View style={{flex:1}}>
                    <text>{JSON.stringify(test)}</text>
                    <Texts text={''} color="grey"/>
                    <Texts text=" 62 856 1234 5678" color="grey"/>
                    <Texts text="Collector" color="grey"/>
               </View>
            </View>
     </ScrollView>
  </SafeAreaView>

when i running the code, the error show like this : [TypeError: undefined is not an object (evaluating 'route.params.test')]

i have update react-navigation/native to latest version, and that is not solve the problem.

Thanks for everyone to helping me..

CodePudding user response:

// send value
navigation.navigate('Home', {test: 'name'});
// getValue
const id = navigation.getParam('test')

CodePudding user response:

You can use the setOptions API:

Check the below example from the docs

React.useLayoutEffect(() => {
    navigation.setOptions({
      title: value === '' ? 'No title' : value,
    });
  }, [navigation, value]);
  • Related