Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Accessing data retrieved from Lockr.get(); #62

@rostaryms

Description

@rostaryms

Hi, so I am trying to utilize Lockr to enable a more advanced data storage system within my website. The problem is I'm not sure how to access the data once I've stored it in a more advanced way using Lockr. My code is below. I'm talking about specifically writing the data in a paragraph within the updateAllDataDisplay function when the page loads. I can get the data logged to the console, but I can't seem to manipulate it properly beyond that. My goal is to have the website display the entry date, entry time, exercise entry, food entry, and mood entry, in that order on the page. Any help? Thanks

// Script

// Goals: Be able to store data with the date, and a journal entry
    // Create dynamic showing of entries
// Be able to have multiple entries for one date in order
// Add food entries
// Add exercise entries
// Add weight entry add weight graph
// Add calorie entry
// Add mood entries for each date
// Add streak showings for entries
// Add calandar functionality
// 


(function(root, factory) {

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = factory(root, exports);
    }
  } else if (typeof define === 'function' && define.amd) {
    define(['exports'], function(exports) {
      root.Lockr = factory(root, exports);
    });
  } else {
    root.Lockr = factory(root, {});
  }

}(this, function(root, Lockr) {
  'use strict';

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/)
    {
      var len = this.length >>> 0;

      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      if (from < 0)
        from += len;

      for (; from < len; from++)
      {
        if (from in this &&
            this[from] === elt)
          return from;
      }
      return -1;
    };
  }

  Lockr.prefix = "";

  Lockr._getPrefixedKey = function(key, options) {
    options = options || {};

    if (options.noPrefix) {
      return key;
    } else {
      return this.prefix + key;
    }

  };

  Lockr.set = function (key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    try {
      localStorage.setItem(query_key, JSON.stringify({"data": value}));
    } catch (e) {
      if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
    }
  };

  Lockr.get = function (key, missing, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
            if(localStorage[query_key]) {
              value = {data: localStorage.getItem(query_key)};
            } else{
                value = null;
            }
    }
    
    if(!value) {
      return missing;
    }
    else if (typeof value === 'object' && typeof value.data !== 'undefined') {
      return value.data;
    }
  };

  Lockr.sadd = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json;

    var values = Lockr.smembers(key);

    if (values.indexOf(value) > -1) {
      return null;
    }

    try {
      values.push(value);
      json = JSON.stringify({"data": values});
      localStorage.setItem(query_key, json);
    } catch (e) {
      console.log(e);
      if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
    }
  };

  Lockr.smembers = function(key, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
      value = null;
    }
    
    return (value && value.data) ? value.data : [];
  };

  Lockr.sismember = function(key, value, options) {
    return Lockr.smembers(key).indexOf(value) > -1;
  };

  Lockr.keys = function() {
    var keys = [];
    var allKeys = Object.keys(localStorage);

    if (Lockr.prefix.length === 0) {
      return allKeys;
    }

    allKeys.forEach(function (key) {
      if (key.indexOf(Lockr.prefix) !== -1) {
        keys.push(key.replace(Lockr.prefix, ''));
      }
    });

    return keys;
  };

  Lockr.getAll = function (includeKeys) {
    var keys = Lockr.keys();

    if (includeKeys) {
      return keys.reduce(function (accum, key) {
        var tempObj = {};
        tempObj[key] = Lockr.get(key);
        accum.push(tempObj);
        return accum;
      }, []);
    }

    return keys.map(function (key) {
      return Lockr.get(key);
    });
  };

  Lockr.srem = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json,
        index;

    var values = Lockr.smembers(key, value);

    index = values.indexOf(value);

    if (index > -1)
      values.splice(index, 1);

    json = JSON.stringify({"data": values});

    try {
      localStorage.setItem(query_key, json);
    } catch (e) {
      if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
    }
  };

  Lockr.rm =  function (key) {
    var queryKey = this._getPrefixedKey(key);
    
    localStorage.removeItem(queryKey);
  };

  Lockr.flush = function () {
    if (Lockr.prefix.length) {
      Lockr.keys().forEach(function(key) {
        localStorage.removeItem(Lockr._getPrefixedKey(key));
      });
    } else {
      localStorage.clear();
    }
  };
  return Lockr;

}));


//localStorage.removeItem('allData');
var allData = [];

init();

function init() {
    /*
    if (Lockr.get('allData') !== null && Lockr.get('allData') !== undefined) {
        allData = JSON.parse(Lockr.get("allData"));
        dataEntries = Lockr.get('dataEntries');
        //console.log(allData);
    } else {
        //console.log('blank exercise data array');
        allData = [];
        dataEntries = 0;
    }
    */
    if (Lockr.get('dataEntries') > 0) {
        dataEntries = Lockr.get('dataEntries');
    }
}

// Create exercise field
let a = document.createElement("input");
a.setAttribute("type", "text");
a.setAttribute("value", "How long did you exercise for today");
a.size = "40";
document.body.appendChild(a);

// Create two <br> between text fields
for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}


// Create diet text field
let e = document.createElement("input");
e.setAttribute("type", "text");
e.setAttribute("value", "What did you eat today");
e.size = "40";
document.body.appendChild(e);

// Create two <br> between text fields

for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}


let f = document.createElement("input");
f.setAttribute("type", "text");
f.setAttribute("value", "Describe your mood in detail today");
f.size = "40";
document.body.appendChild(f);

for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}

// Create save data button
let saveDataBtn = document.createElement("button");
saveDataBtn.innerHTML = "Save Data";   
document.body.appendChild(saveDataBtn);


for (let i = 0; i < 3; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}

// Create clear data button
let clearDataBtn = document.createElement("button");
clearDataBtn.innerHTML = "Clear Data";   
document.body.appendChild(clearDataBtn);


// Create allData Header
let b = document.createElement("p");
let c = document.createTextNode('Saved Data:');
b.appendChild(c);
document.body.appendChild(b);


(function updateAllDataDisplay() {
    for (var i = 0; i < dataEntries; i++) {
        let currentEntry = Lockr.get(`data${i}`);
        console.log(currentEntry);
        let a = document.createElement("p");
        let b = document.createTextNode('blah');
        a.appendChild(b);
        document.body.appendChild(a);
    }
})();



/*
Goal: create buttons that toggle between showing a user inputted pragraph tracking their moood on the day they exercised for x number of inputted hours
*/

saveDataBtn.onclick = function () {
    var date = new Date();
    let day = date.getDate();
    let month = date.getMonth();
    let year = date.getFullYear();
    let hours = date.getHours();
    let mins = date.getMinutes();
    let secs = date.getSeconds();
    //allData.push(`${day}/${month + 1}/${year} (${hours}:${mins}:${secs}): ${a.value}. ${e.value}. ${f.value}.`);
    //localStorage.setItem("allData", JSON.stringify(allData));
    //Lockr.set('allData', JSON.stringify(allData));
    
    //Lockr.set('newData', [{first: `${a.value}`}, {second: `${e.value}`}, {third: `${f.value}`}]);
    //console.log(Lockr.get('newData'));
    
    dataEntries += 1;
    Lockr.set(`data${dataEntries}`, [{date:`${day}/${month + 1}/${year}`, time: `${hours}:${mins}:${secs}`, exerciseHours: a.value, food: e.value, mood: f.value}, {test: 'testing'}]);
    Lockr.set('dataEntries', dataEntries);
    console.log(Lockr.get(`data${dataEntries}`));
    console.log(dataEntries);
}

clearDataBtn.onclick = function () {
    //localStorage.removeItem('allData');
    for (var i = 0; i < dataEntries; i++) {
        Lockr.rm(`data${i}`);
    }
    dataEntries = 0;
    //Lockr.rm('');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions