gruns / ImmortalDB

:nut_and_bolt: A relentless key-value store for the browser.
MIT License
3.05k stars 61 forks source link

Synchronous get / set? #51

Open adsee42 opened 3 years ago

adsee42 commented 3 years ago

Very helpful package! Thank you.

I'm using ImmortalDB with React to save some page state to local. I would like to init a component's state by loading locally stored state, like:

const MyComponent = () => {
  const [state, setState] = useState(() => {
    return ImmortalDB.get('key')
  })
}

But ImmortalDB.get returns a Promise, so the above line would be return await ImmortalDB.get('key'). And React's useState does not support async functions, so a synchronous get would be very helpful

gruns commented 3 years ago

Hey! The problem with a synchronous API is that not all the datastores underlying ImmortalDB offer synchronous APIs. Like IndexedDB:

Operations performed using IndexedDB are done asynchronously, so as not
to block applications. IndexedDB originally included both synchronous
and asynchronous APIs. The synchronous API was intended for use only
with Web Workers but was removed from the spec because it was unclear
whether it was needed. However, the synchronous API may be reintroduced
if there is enough demand from web developers.

If you need a synchronous API, one potential future feature for ImmortalDB would be to offer a sync API if ImmortalDB was created with only data stores that in turn all offer synchronous APIs. E.g.

const syncStores = [await SynchronousStore1(), await SynchronousStore2(), ...]
const db = new ImmortalStorage(syncStores)

db.get(key) // Synchronous.

But this 1) limits the data stores that can be used and 2) doesn't seem worth the effort nor API complication.

The better solution, to me, would be for React's useState() to support async functions. It's not just ImmortalDB; if any React user wanted to interact with a plain old IndexedDB database in useState(), async would be required, too.