varasto

Package Version Hex Docs

Typed access to the Web Storage API, i.e. LocalStorage and SessionStorage.

This package is only for the JavaScript target. It depends on plinth, which implements the lower level (string only) Web Storage API access. Thus, if you only intend to read and write string values, you may use plinth directly.

Usage

Varasto uses JSON as the storage format. To use it, you will need to construct a TypedStorage value that encapsulates a reader and a writer to convert the value to and from gleam/json.Json.

An example where the data type is a list of integers:

import gleam/dynamic
import gleam/json
import plinth/javascript/storage
import varasto

// Reader that decodes a Dynamic to a list of integers
fn int_list_reader() {
  dynamic.list(dynamic.int)
}

// A writer that converts a list of integers to a Json value
fn int_list_writer() {
  fn(val: List(Int)) { json.array(val, json.int) }
}

// First use plinth to get the low level storage
let assert Ok(local) = storage.local()

// Construct TypedStorage with the reader and writer
let s = varasto.new(local, int_list_reader(), int_list_writer())

// Set a value
varasto.set(s, "Foo", [1, 2, 3])

// Returns Ok([1, 2, 3])
varasto.get(s, "Foo")

Installation

This package can be added to your Gleam project:

gleam add varasto

and its documentation can be found at https://hexdocs.pm/varasto.

Search Document