0
0
DenoHow-ToBeginner ยท 3 min read

How to Get Value from Deno KV: Simple Guide

To get a value from Deno KV, use the asynchronous kv.get(key) method, where key is the identifier for the stored data. This returns a promise that resolves to an object containing the value under the value property if the key exists.
๐Ÿ“

Syntax

The basic syntax to get a value from Deno KV is:

  • kv.get(key): Asynchronously fetches the value stored at key.
  • key: Can be a string or an array of strings/numbers to represent nested keys.
  • The method returns a promise resolving to an object with a value property holding the stored data or null if not found.
typescript
const kv = await Deno.openKv();
const result = await kv.get("myKey");
console.log(result.value);
Output
value stored at 'myKey' or null if not found
๐Ÿ’ป

Example

This example shows how to store a value and then retrieve it from Deno KV.

typescript
const kv = await Deno.openKv();

// Store a value
await kv.set("username", "alice");

// Get the value
const result = await kv.get("username");

if (result.value !== null) {
  console.log("Value found:", result.value);
} else {
  console.log("Key not found.");
}

await kv.close();
Output
Value found: alice
โš ๏ธ

Common Pitfalls

Common mistakes when getting values from Deno KV include:

  • Not awaiting the kv.get() call, which returns a promise.
  • Assuming the result is the value directly instead of an object with a value property.
  • Not handling the case when the key does not exist, which returns { value: null }.

Always check if result.value is null before using it.

typescript
/* Wrong way: */
const result = kv.get("missingKey"); // forgot await
console.log(result.value); // Error: result is a Promise

/* Right way: */
const resultCorrect = await kv.get("missingKey");
if (resultCorrect.value === null) {
  console.log("Key not found.");
} else {
  console.log(resultCorrect.value);
}
Output
Key not found.
๐Ÿ“Š

Quick Reference

MethodDescriptionReturn Value
kv.get(key)Fetches the value for the given keyPromise resolving to { value: storedValue | null }
kv.set(key, value)Stores a value at the given keyPromise
keyString or array representing the key pathUsed to identify stored data
โœ…

Key Takeaways

Use await with kv.get(key) to retrieve the stored value asynchronously.
The result of kv.get is an object with a value property, not the value directly.
Check if result.value is null to handle missing keys safely.
Keys can be strings or arrays for nested data in Deno KV.
Always close the KV store with kv.close() when done.