Skip to content

Instantly share code, notes, and snippets.

@rafaelkendrik
Last active May 30, 2020 00:18
Show Gist options
  • Save rafaelkendrik/3fbbdf0e8039f97ea2fb9e8ed99b60b1 to your computer and use it in GitHub Desktop.
Save rafaelkendrik/3fbbdf0e8039f97ea2fb9e8ed99b60b1 to your computer and use it in GitHub Desktop.
export const ACCOUNT_ID_KEY = 'account-id'
export const ACCOUNTS_KEY = 'accounts'

const get = (key, options = {}) => {
  const value = localStorage.getItem(key)

  return (options.parse)
    ? JSON.parse(value)
    : value
}

const save = (key, rawValue, options = {}) => {
  const value = (options.stringify)
    ? JSON.stringify(rawValue)
    : rawValue

  localStorage.setItem(key, value)

  const promisify = new Promise(resolve => {
    const frame = setInterval(isStored, 200)
    const clearFrameInterval = () => clearInterval(frame)

    let stored = ''

    function isStored () {
      if (stored.length) {
        clearFrameInterval()
        resolve(stored)
        return
      }

      stored = localStorage.getItem(key)
    }
  })

  return promisify
}

export const getAccountId = () => get(ACCOUNT_ID_KEY)
export const saveAccountId = accountId => save(ACCOUNT_ID_KEY, accountId)

export const getAccounts = () => get(ACCOUNTS_KEY, { parse: true })
export const saveAccounts = accounts => save(ACCOUNTS_KEY, accounts, { stringify: true })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment