Khắc Thắng
Khắc Thắng

Reputation: 27

How can I transfer data between screens but not switch screens in react native

I have a problem how to pass user data after logging in via the 'profile' screen BUT it is not switched to the profile screen? I only know the code below is the data transfer is complete then the screen will switch? I searched a lot on the internet but there was none or maybe I don't know how to search for this keyword.

    this.props.navigation.navigate('Profile', {
                  data: this.state.data
                });

Upvotes: 0

Views: 565

Answers (2)

Edison Pebojot
Edison Pebojot

Reputation: 318

If you don't want to switch screens but want to pass data across screens, first, since you don't want to switch screens, you don't need this:

this.props.navigation.navigate('Profile', {
     data: this.state.data
});

And instead, you need this:

function_name() {
  // some code we will discuss below...
}

Second, since you want the data available across screens or more specifically send the data across screens but not go to that screens, you can use local storage like Async Storage (or SQL lite for big projects). That way, the data is available between screens, but not go to that screens.

For example, in Async Storage, you can store data in local but not switch screens:

async storeData(key, value) {
   try {
     await AsyncStorage.setItem(key, value);
   }
}


async button(key, value) {
  await this.storeData(key, value);
  // In case you like to switch screens anywhere you want,
  // you can uncomment the code below:
  // this.props.navigation.navigate('you screens')
}

render() {
  return(
    <Button onPress={() => this.button("data", this.state.data) } />
  );
}

Then, you can retrieve it anywhere you want on your screens, whether you want to switch screens or not:

async getData(key) {
   try {
     const value = await AsyncStorage.getItem(key);
     if (value !== null) {
        return value;
     }
   }
}

async button(key) {
  const data = await this.getData(key);
 }

 render() {
   return(
      <Button onPress={() => this.button("data") } />
   );
}

Upvotes: 0

MoKhajavi75
MoKhajavi75

Reputation: 2712

You can use Async Storage to access data after switching navigators.

Also, I'm not sure what's the problem with passing data with navigation.navigate. You can use getParam() to get data on the next screen.

Update

Send data:

this.props.navigation.navigate('Profile', {
  nickName: 'MohamadKh75'
});

Get data in Profile screen:

const name = this.props.navigation.getParam('nickName', 'defaultValue'); // name will be 'MohamadKh75'
const age = this.props.navigation.getParam('age', 123); // as we didn't pass 'age', the value is 123

Check here for more information!

Upvotes: 1

Related Questions