Javascript KV Storage Introduction Tutorial

javascript
Published on November 4, 2019

Use-Cases of this Tutorial

  • Know about the KV Storage API.
  • Know how to save data in the browser asynchronously.

KV Storage API is an asynchronous way to save data in the browser using Javascript Promises. Its asynchronous nature guarantees that the performance of the application is not impacted.

Currently LocalStorage and IndexedDB APIs are two ways of saving data in the browser. While LocalStorage is meant for simple cases, IndexedDB is meant for complex cases such as "executing queries in the browser".

Why Introduce KV Storage ?

While the localStorage API is really simple to use, the problem is that it is synchronous — during the time API is being used, the main Javascript thread is blocked and application becomes unresponsive. For simple webpages this probably wouldn't matter much, but for for high performance Javascript applications, this synchronicity becomes a bottleneck.

IndexedDB is an asynchronous API, but its learning curve is steeper. It is not very direct to use.

So combining the best of localStorage and IndexedDB, KV Storage has been introduced. It is wrapped on top of the IndexedDB API, so it is not actually a new storage API. KV Storage has the same performance benefits as IndexedDB API, and it is fairly simple to use just like localStorage API.

KV Storage API is asynchronous. For example, if we call the API to save some data in browser, the call will be made and returned immediately, and code following that will keep on executing. At a later time when the data is actually saved, or if an error occurs, we will be notified.

Using KV Storage APIs

KV Storage is actually a browser built-in module (web's first built-in browser module to be precise). This module needs to be imported in the webpage prior to using its API.

<!-- script type="module" -->
<script type="module">
	import storage from 'std:kv-storage';

	// rest of the code using KV Storage APIs
</script>

KV Storage APIs

All KV Storage APIs return a Promise. This Promise will be resolved or rejected at a later time. We can handle success or error using then() and catch() methods of the Promise, or use the await operator inside an async function.

  • Saving an item to storage

    To save an item in the KV Storage, the set() method is called. This method accepts 2 parameters, the key and it's value respectively.

    If the value is passed as undefined the item is deleted from the storage.

    This method returns a Promise that resolves with undefined.

    // sets the key "my_key" with value "my_value"
    storage.set("my_key", "my_value")
    	.then(function() {
    		console.log("Key was set");
    	})
    	.catch(function() {
    		console.log("Key was not set");
    	});
    
    // calling api using async-await
    (async function() {
    	try {
    		await storage.set("my_key", "my_value");
    		console.log("Key was set");
    	}
    	catch {
    		console.log("Key was not set");
    	}
    })();
    
  • Getting an item from storage

    To get an item from the KV Storage, the get() method is called. The key whose value requires to be retrieved is passed to it as the only parameter.

    The method returns a promise that resolves to the value of the key. If the key does not exists in the storage, undefined is returned.

    // get "my_value" key from storage
    storage.get("my_key")
    	.then(function(value) {
    		if(value === undefined)
    			console.log("Key was not found");
    		else
    			console.log("Value of key is " + value);
    	})
    	.catch(function() {
    		console.log("Key was not found");
    	});
    

    Note that the resolve and reject above are from the wrapping Promise object.

    // calling api using async-await
    (async function() {
    	try {
    		var value = await storage.get("my_key");
    
    		if(value === undefined)
    			console.log("Key was not found");
    		else
    			console.log("Value of key is " + value);
    	}
    	catch {
    		console.log("Key was not found");
    	}
    })();
  • Deleting an item from storage

    To delete a key from the KV Storage, the delete() method is called. This method accepts one parameter, the name of the key that has to be removed.

    This method returns a Promise that resolves with undefined.

    // deletes the key "my_key"
    storage.delete("my_key")
    	.then(function() {
    		console.log("Key was removed");
    	})
    	.catch(function() {
    		console.log("Key was not removed");
    	});
    
    // calling api using async-await
    (async function() {
    	try {
    		var value = await storage.delete("my_key");
    		console.log("Key was removed");
    	}
    	catch {
    		console.log("Key was not removed");
    	}
    })();
    
  • Removing all items from storage

    In order to remove all entries from the KV Storage, the clear() method is called. This method accepts no parameter.

    This method too returns a Promise that resolves with undefined.

    // removes all keys and values
    storage.clear()
    	.then(function () {
    		console.log("All keys were removed");
    	})
    	.catch(function() {
    		console.log("Keys were not removed");
    	});
    
    // calling api using async-await
    (async function() {
    	try {
    		await storage.clear();
    		console.log("All keys were removed");
    	}
    	catch {
    		console.log("Keys were not removed");
    	}
    })();
    
In this Tutorial