Browse Category: Javascript

How to implement In-browser Database for offline use

If you are familiar with Laravel Eloquent, this is going to look familiar.

We are going to use a JS library very similar to Eloquent called collect.js. With this little beast in place, all you have to do is use it to transform your data into Eloquent collection in JavaScript, and use all Eloquent magic on the frontend:

 


// Fake db (aka fake news)

import collect from 'collect.js'

const collection = collect({
    users: [
        { id: 1, firstname: 'Jane', lastname: 'Doe', gender: 'F' },
        { id: 2, firstname: 'John', lastname: 'Doe', gender: 'M' },
        { id: 3, firstname: 'Penelope', lastname: 'Cruz', gender: 'F' },
        { id: 4, firstname: 'Eva', lastname: 'Longoria', gender: 'F' },
        { id: 5, firstname: 'Cristiano', lastname: 'Penaldo', gender: 'M' }
    ],

    cities: [
        { id: 1, name: 'Sydney', country: 'Australia', humans: 4873217, kangaroos: 9321893, snakes: 22432645},
        { id: 2, name: 'Douala', country: 'Cameroon', humans: 5221943, kangaroos: 0, snakes: 2981023},
        { id: 3, name: 'Villetaneuse', country: 'France', humans: 32987, kangaroos: 0, snakes: 876432}
    ],

    friends: [],
    todos: [], // duh
    andSoOn: []
})

// Important bit...
localStorage.setItem('fake_db', JSON.stringify(collection))

And there, my friend, you have persisted your entire fake database to the localStorage. If and when you reload the page, or quit and reopen the browser, your data is not lost and you can query if offline like this

// Read and query fake_db
let fakeDB
const data = localStorage.getItem('fake_db')
if (data) {
    fakeDB = collect(JSON.parse(data))
}

const females = fakeDB.get('users').where('gender', 'F').all()
console.log(females) // (3) [{...}, {...}, {...}]
//The above array will contain users 1, 3 & 4

As you can see, it looks and behaves like helpers function from Laravel Collection. You could wrap this as a service or use with one of the cool kids like Redux or vuex .

Keep in mind though, localStorage is limited in size (MB).  How big? I have no clue. I wanted to Google it and put it here, but man, I’ll leave it for another day. And yeah, Ronaldo moved to Juve. But all good. We’ll sort it out. As long as we don’t get relegated, we’ll sort it out.

Disclaimer: If your code does not work, I have no idea why. If your code works, I have no idea why.

Get user timezone with Javascript

In 2017 it’s relatively easy to get the user timezone with countless of packages available. Nonetheless, there are easier, shorter, faster way to get the user timezone using just vanilla JavaScript, which takes it from the user’s browser if set properly.


var split = new Date().toString().split(" ");
var timeZoneFormatted = split[split.length - 2] + " " + split[split.length - 1]; 

console.log(timeZoneFormatted)
//outputs "GMT+1100 (AEDT)"

Manchester is red! So is my bank account.