Reputation: 11
So I got an array with a ton of fields that are bound to <Text>
Now I also have a button in here. What I want to do is onclick I want to go to a function onSubmit which also takes the value session.gameId
and puts it in asyncstorage.
{this.state.sessions.map((session, index) => {
return (
<View style={styles.cardContainer}>
<Text style={styles.title} >{session.title}</Text>
<Text style={styles.text}>Organisator: {session.organizer}</Text>
<Text style={styles.text}>Hoofd Thema: {session.mainTheme}</Text>
<Text style={styles.text}>Aantal Deelnemers: {session.numberParticipants}</Text>
<Text style={styles.text}>Game Id: {session.gameId}</Text>
<TouchableOpacity style={styles.buttonContainer} >
<Text style={styles.buttonText} onPress={this.onSubmit} value={session.gameId} >
Selecteer
</Text>
</TouchableOpacity>
But I have no idea how my onsubmit can handle both an event to change page after storing the value into asyncstorage
Please help
Upvotes: 1
Views: 1315
Reputation: 560
Not sure if I'm understanding your question correctly, but if you're trying to store the value of session.gameId into AsyncStorage and then change the page, your function may look something like this:
changePage() {// functionality to navigate to another page}
/*
* have onSubmit be an async function so you use the 'await' keyword
* await forces an asynchronous line of code to wait until the operations is done before moving forward
*/
async onSubmit(gameId) {
try {
await AsyncStorage.setItem('@store:key', gameId)
} catch(error) {
// handle error
}
// however you are changing page, handle it here
// this code wont run until gameId has been stored in async storage
this.changePage()
}
You would also need to pass the gameId to the function to actually call it now:
onPress={() => this.onSubmit(session.gameId)}
Take a look at how async functions can make your life easier :)
Upvotes: 1
Reputation: 7654
I'm answering this assuming that when you say your onSubmit
triggers "an event to change page", you mean that it navigates to another screen.
If so, you seem to be asking for something like this:
onSubmit = async gameId => {
try {
await AsyncStorage.setItem('gameId', gameId)
// Success: navigate away here
this.props.goToMyOtherScreen()
} catch {
// Handle error
}
}
To get gameId
into your submit handler, you could use an inline anonymous function:
<Text
style={styles.buttonText}
onPress={() => this.onSubmit(session.gameId)}>
Upvotes: 0