Search code examples
javascriptcheckboxmeteor-accountsmeteor-helper

Sync Meteor checkbox state with database


I have a checkbox in my application and what i am trying to do is store the state of checkbox i.e if its checked or not. Once user checks the checkbox its store it in to database and when next time he visit the page it should be checked.

I am trying to use session and it works across different pages on same application but once i reload the page its gone. I guess session works for temporary data. What should be use for permanent data?

HTML

<template name="test">
    <input type="checkbox" id="check" checked="{{Checked}}"> 
</template>

JS

Template.Test.events({
    'click #check':function(e){
        Session.set('Checked', e.target.checked);
    }
})

Template.Test.helpers({
    Checked: function(){
        return Session.get("Checked");
    }
})

Solution

  • http://meteorpad.com/pad/u3D5TDaMDDg8Aw2ie/Leaderboard

    How long do certain Meteor data sources live for?

    Since this checkbox setting is synced to the user that's logged in, you want to save this setting on the user that's logged in.

    HTML

    <body>
    
        {{> loginButtons }}
    
        {{#if currentUser}} 
          {{> Test }}
        {{/if}}
    
    </body>
    
    
    <template name="Test">
      <div class="container">
        <div class="row">
          <div class="col-xs-8 col-xs-offset-2">
            <input type="checkbox" id="check" checked="{{isChecked}}"> 
          </div>
        </div>
      </div>
    </template>
    

    The Meteor Users collection is kind of special and you need to do some reading on how it functions

    But for now, what you need to know is that from the client:

    • You can access the currently logged in user with Meteor.user()

    • By default Meteor publishes the Meteor.user().profile field to the client.

    • From the client, you can only edit the Meteor.user().profile field.

    • In order to edit/update a Meteor user, you must put in the precise userId (ID of the user document) in a Mongo update command - Meteor.users.update({_id: userId}, {$set: {"profile.isChecked": isChecked}});

    JS

    Template.Test.events({
        'click #check':function(e){
          var userId = Meteor.user()._id;
          var isChecked = e.target.checked;
          Meteor.users.update({_id: userId}, {$set: {"profile.isChecked": isChecked}}); 
        }
    })
    
    Template.Test.helpers({
        isChecked: function(){
          return Meteor.user().profile.isChecked;
        }
    })
    
    Accounts.ui.config({
      passwordSignupFields: "USERNAME_ONLY"
    });