Search code examples
javascriptreactjsreact-nativereduxjsx

Do I need to use Redux or Context API


I have an application where users log in first as usual. My app has several screens which are navigated by react-native-navigation.

On every screen other than login, I need to know which user is using my app since the content is specialized by his/her uniqueID. I get that uniqueID when the user successfully login but I don't know how to pass this uniqueID to other screens.

Do I need to use Redux or context API in order to handle this problem or is there another way to pass this data between screens back and forth without changing the project?

Here is my App.js:

import React, { Component, PropTypes } from 'react';
import { AppNavigator } from './components/Navigator';


 class App extends React.Component {
  render() {
    return (
      <AppNavigator />
    );
  }
}
export default App;

Here is my Navigator component:

const Stack = createStackNavigator({

    Main: { screen: MainScreen },
    Login: {screen: LoginScreen},
    Profile: {screen: ProfileScreen},
    NewSurvey: {screen: NewSurveyScreen},
},
    {
        initialRouteName: 'Login',
        headerMode: 'none',
        navigationOptions: {
            headerVisible: false,
            gesturesEnabled: false,
        }
    })

export const AppNavigator = createAppContainer(Stack);


Solution

  • To pass data to other screens you can use React Navigation navigate method and passing some data inside of it.

    i don't know how you stored you Data whether using a database like Realm or SQLite etc... but whenever you fetch data from there and you want to pass it to other screens do this like below:

    this.props.navigation.navigate('SecondPage', {
            //your data goes here
            });
    

    for example :

    this.props.navigation.navigate('Homescreen', {
           username: this.state.username,
           });
    

    and then you can get that data like below:

    const username = navigation.getParam('username', 'Default'); //default is a value that will be used if there was no username passed