Wonka
Wonka

Reputation: 8674

MobX - Observable object grabbing only changed fields?

I have a MobX store setup with an observable object that has default values, and whose values gets populated from the server on load of react native scene. 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: 0
    }
}

On the RN side, these values change to this:

class UserPreferencesStore {
    @observable userPreferences = {
        receive_upvotes_mail: 1,
        receive_answers_mail: 1,
        receive_comments_mail: 0
    }
}

I am not sure how to get only the changed items to send to the server. Any idea? Also, is this the most efficient way to use mobx for this situation, an observable object, even if I have 20 fields?

Upvotes: 1

Views: 540

Answers (1)

mweststrate
mweststrate

Reputation: 4978

That should be a matter of establishing a separate autorun or reaction for each field:

class UserPreferencesStore {
    @observable userPreferences = {
        receive_upvotes_mail: 1,
        receive_answers_mail: 1,
        receive_comments_mail: 0
    }

    constructor() {
        Object.keys(this.userPreferences).forEach(setting => {
            reaction(
                // whenever a new value is produced...
                () => this.userPreferences[setting],
                // ..run this effect
                (newValue) => storeSettingOnServer(setting, newValue)
            )
        })
    }
}

Upvotes: 2

Related Questions