DEV Community

Cover image for Usando o local storage a seu favor
Jhonatan Henkel
Jhonatan Henkel

Posted on

Usando o local storage a seu favor

Olá, imagine a seguinte situação, você tem que implementar os dados das taxas básicas do Brasil (Selic, CDB, IPCA, etc...) em uma dashboard, em algum momento você vai precisar bater em um endpoint externo. Chamar esse endpoint a cada carregamento dessa página não é uma opção...

Colocar em local storagem é uma ótima opção, mas para renovar esse item no local storage temos que ter um certo controle sobre esse item.

para isso em minha aplicação eu desenvolvi uma classe que fica responsável por colocar e recuperar itens do local storage.

Vamos ao código:

import CalendarTools from './calendarTools'

const LocalStorageTools = {
    storage: {
        getStorageItem: function(key) {
            const itemInStorage = localStorage.getItem(key)
            if (itemInStorage) {
                const itemParsed = JSON.parse(itemInStorage)
                const now = CalendarTools.getToday()
                if (now.getTime() < itemParsed.expiry) {
                    return itemParsed.value
                }
                this.removeStorageItems(key)
            }
            return null
        },
        setStorageItem: function(key, value, expireTimeMs) {
            const expiry = expireTimeMs ?? CalendarTools.threeHoursInMs()
            localStorage.setItem(key, JSON.stringify({
                value,
                expiry: CalendarTools.getToday().getTime() + expiry
            }))
        },
        removeStorageItems: function(...keys) {
            keys.forEach((key) => {
                localStorage.removeItem(key)
            })
        }
    }
}

export default LocalStorageTools
Enter fullscreen mode Exit fullscreen mode

Vamos a explicação, como controle eu uso uma string que armazena o tempo que o item irá expirar, que sempre será o tempo atual somado com um tempo de expiração em ms, com isso, no local storage sempre teremos o item como objeto com dois atributos, um expiry e um value, que é onde vai ficar o que queremos armazenar.

Sendo assim a função de salvar o item em local storage vai ficar responsável por salvar no formato mencionado acima. A função de buscar vai ter que validar se o item está expirado, se não tiver devolve o atributo value, se tiver, retorna null e apaga o item do storage.

Com isso temos um cache em local storage para coisas simples como por exemplo esses dados das taxas, já que é algo que não muda toda hora e não queremos bater na API externa a todo momento.

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed: Zero in on just the tests that failed in your previous run
  • 2:34 --only-changed: Test only the spec files you've modified in git
  • 4:27 --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • 5:15 --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • 5:51 --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay