typicode / lowdb

Simple and fast JSON database
MIT License
21.58k stars 924 forks source link

Using lowdb in svelte causes 500 error #564

Closed midoublelo closed 1 year ago

midoublelo commented 1 year ago

Hello,

I am attempting to use lowdb in my svelte project however am having trouble getting it up and running.

` import { LowSync } from 'lowdb'; import { LocalStorage } from 'lowdb/browser';

const adapter = new LocalStorage('db');
const db = new LowSync(adapter);

db.read()
db.data ||= { books: [] }

db.data.books.push({ title: 'test' })

console.log(db.data)

` (unsure why the formatting messed up, hopefully still readable)

When importing LocalStorage like this, VS Code tells me that it "cannot find module 'lowdb/browser' or its corresponding type declarations' and when testing my project I get this error in the console:

ReferenceError: localStorage is not defined at new LocalStorage (file:///C:/.../libmanager-svelte/node_modules/lowdb/lib/adapters/LocalStorage.js:4:20) at +page.svelte:23:14 at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22) at Object.default (root.svelte:42:40) at Object.default (/src/routes/+layout.svelte:80:36) at AppShell.svelte:62:62 at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22) at eval (/src/routes/+layout.svelte:49:92) at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22) at root.svelte:41:39

How can I fix this issue and get LowDB working in Svelte?

Valexr commented 1 year ago

I think you need check for availability browser storage before initialize adapter...😉