Reputation: 8674
I have a MobX store, and a react native class setup and working, but not as intended. I have a list of observable user preferences in the UserPreferencesStore
like this:
class UserPreferencesStore {
@observable userPreferences = {
receive_upvotes_mail: 0,
receive_answers_mail: 0,
receive_comments_mail: 1
}
}
In the react native class, I want to update the above observables based on onPress of TouchableHighlight
like this:
<TouchableHighlight onPress={() => this.onPressPreference('receive_upvotes_mail')}>
<Image source={require('images/Email.png')}
style={UserPreferencesStore.userPreferences.receive_upvotes_mail == 1 && styles.active} />
</TouchableHighlight>
<TouchableHighlight onPress={() => this.onPressPreference('receive_answers_mail')}>
<Image source={require('images/Email.png')}
style={UserPreferencesStore.userPreferences.receive_answers_mail == 1 && styles.active} />
</TouchableHighlight>
<TouchableHighlight onPress={() => this.onPressPreference('receive_comments_mail')}>
<Image source={require('images/Email.png')}
style={UserPreferencesStore.userPreferences.receive_comments_mail == 1 && styles.active} />
</TouchableHighlight>
and here is the onPressPreference
action to update the observables that does not work...
@action onPressPreference = (preferenceName) => {
// alert(preferenceName);
UserPreferencesStore.userPreferences.preferenceName = UserPreferencesStore.userPreferences.preferenceName == 0 ? 1 : 0;
}
The preferenceName
parameter gets passed perfectly, as the alert shows it, but it does not seem to work when "appended" here UserPreferencesStore.userPreferences.preferenceName
to update the passed preference observable store value.
However, If I create 3 actions, one for each preference, and trigger them onPress, then it works and the observable updates the value correctly in the store, but it's a lot of code repeated, and I really want to get it to work with the passed parameter to a single action.
Any idea how to get the passed parameter to work with the single action to update the respective observable's value?
Upvotes: 1
Views: 1624
Reputation: 25329
You need to use bracket notation to access a property with variable name.
UserPreferencesStore.userPreferences[preferenceName] = UserPreferencesStore.userPreferences[preferenceName] == 0 ? 1 : 0;
Upvotes: 3