I'm working on my first React project and I would like to use some kind of global variables but I'm having some trouble with understanding the flow and scope of variables in React.
After the user logs in I'm saving the username in the AsyncStorage, so it will be remembered, the next time he/she uses the app.
const loginUser = (username, password) => {
// ... imaginary login fuctionality ...
this.saveUserName(username);
}
saveUserName = async (username) => {
try {
await AsyncStorage.setItem("username",username);
} catch (error) {
console.log(error.message);
}
};
After the authentication succeeds and the username gets stored, i use react-navigation to navigate to the HomeScreen.
saveUserName = async (username) => {
try {
await AsyncStorage.setItem("username",username);
this.navigation.navigate("Home")
} catch (error) {
console.log(error.message);
}
};
So I arrive on my Homescreen where I would like to show a welcome message containing the username.
return (
<View style={styles.loginContainer}>
<Text style={style.welcome}>Welcome [username should come here]</Text>
</View>
)
Since the username will remain unchanged throughout the whole application, I would like to place it in some sort of 'global' variable, so I can be retrieved throughout the whole application. I tried retrieving it from the AsyncStorage again on the homescreen but because it's asynchronous, the page is already rendered.
Since i'm using react-navigation, i can retrieve the name from the AsyncStorage and pass it in the navigation function :
let username = await AsyncStorage.getItem("username");
this.props.navigation.navigate("Login", {
username: username,
});
This works, but it feels like a bad practice to manually pass this variable to every page where I want to show the username. Since the username doesn't change, I guess it would be overkill to retrieve it multiple times from the AsyncStorage?
Is there a way to retrieve all the values from AsyncStorage just once, and then store them in some kind of global variable, so that they can be used throughout the whole application?
I've read some articles stating that I can pass these variables to the state of my app, but I seem to understand that the variables only would be passed from parent to child? I made the Homescreen with a functional component which I understand is stateless, so I guess this isn't an option?
Many thanks in advance