Coder Social home page Coder Social logo

localbase's People

Contributors

charlieknoll avatar dannyconnell avatar hasibweb avatar radio-miskovice avatar samuk190 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

localbase's Issues

Please make it archive

@dannyconnell Hello Sir, I really liked this repo and really want to contribute to it. As there are certainly a lot of bugs but I think it is normal for a small project, But I fear If any beginner would fall for any bug or something like that, So I want that you should make it clear in the readme with a big headline that repo is no longer maintained. Don't take me wrong here but I want you to make it clear for the developers you are gonna watch your videos and are gonna use it blindfolding and then gonna end up ruining their projects due to their own lack of knowledge. Like I have seen some issues about filter function is not working and it is not your problem it is IndexedDB problem the thing is that you never really can save the key as int so you can't sort it like an index table, So I want you to make them acknowledge that you are no longer maintaining the project for the time being.

Database creation

Is there a way to just create a database and not initialize it with any collection ? Sorry if this is a silly question

Update doesn't work when passing an array as a field value

Love this library, but cant figure out what I'm doing wrong here. Thanks in advance.

My doc looks like this:

{
  "id":"bdfa1a2b-7950-4c97-935e-a4f37d99345b",
  "title":"",
  "text":"",
  "color":"white",
  "notebook":"",
  "modified":"2020-09-20T06:44:58.587Z",
  "created":"2020-09-20T06:44:58.587Z",
  "fave":false,
  "trash":false,
  "tags":[],
  "shares":[],
  "attachments":[]
  }
}

I add it successfully, no issues
Screenshot_20200920_001843

But when I go to update it, I get the following error:

Uncaught ReferenceError: update is not defined
    at updateObject (updateObject.js?c9f3:6)
    at eval (update.js?0aaf:19)
    at IDBRequest.req.onsuccess (localforage.js?a002:979)

Here is the update code:

    UPDATE_NOTE(state, payload) {
      console.log("update payload: ", payload);
      db.collection("NoteRiot")
        .doc({ id: payload.id })
        .update(payload.updates)
        .then((response) => {
          console.log("note update res: ", response);
          let idx = state.notes.findIndex((note) => note.id === payload.id);
          let update = Object.assign(state.notes[idx], payload.updates);
          state.notes.splice(idx, 1, update);
        })
        .catch((error) => {
          console.log("error updating local db: ", error);
        });
    },

and update payload content:

update payload:  
{id: "bdfa1a2b-7950-4c97-935e-a4f37d99345b", updates: {…}}
id: "bdfa1a2b-7950-4c97-935e-a4f37d99345b"
updates:
attachments: Array(0)
color: "white"
created: 1600586238190
fave: false
id: "bdfa1a2b-7950-4c97-935e-a4f37d99345b"
modified: 1600586247499
notebook: ""
shares: Array(0)
tags: Array(0)
text: "<p>bar</p>"
title: "foo"
trash: false

Screenshot_20200920_002101

Orderby Two Values

Is there a way to orderby two values instead of just one?

while this works:

db.collection('people')
      .orderBy('l_name')

This doesn't:
db.collection('people')
.orderBy('l_name','f_name')

Delete Document by Index

Hello, I just want to know if it's possible to delete a document by it's index . I couldn't find any information about that in the docs.

My delete isn't working.

I don't know why when I click to delete the item, nothing happens, so when I refresh the page, the item will now be deleted. And when I delete second time and refresh, the first Item will be restored. I want to delete progressively without refresh the page. Thank you
`import React, { useState, useEffect } from 'react'
import notifications from '../mock/notifications.json'
import Localbase from 'localbase'

export default function Notification() {
const [data, setData] = useState([])

let db = new Localbase('db');
db.config.debug = false
notifications.map((item, index) => {
    return db.collection('notification').add({
         id: item.id, 
         excerpt: item.excerpt,
         content: item.content, 
         date: item.date

}, `my-key${index}`)
})


useEffect(  () => {
      function getData(){
     db.collection('notification').get().then(response => {
            console.log(response); 
            setData(response)
        })
        .catch(error => {
            console.log(error)
        });
 }    
 getData();
}, [])

function onDelete(index){
    db.collection('notification')
      .doc(`my-key${index}`)
      .delete()
      .then(response => {
          console.log(response)
      })
      .catch(error => {
          console.log(error)
      })
} 
return (
    <>
    <ul>
        { data.map((item, index) => 
           (
        <li key={index} >
           <div>
              <h4>{item.date}</h4>
              <p>{item.excerpt}</p>
              <button onClick={()=> 
                    onDelete(index)
               }
              >Delete</button>
          </div>
          </li>
        ) )}
    </ul> 
    </>
)

}`

Set a collection (overwrite) - problem

Hi, when I use example from readme

db.collection('users')
  .set([
    {
      id: 1,
      name: 'Bill',
      age: 48
    },
    {
      id: 2, 
      name: 'Paul',
      age: 28
    }
  ])

I got error
Data passed to .set() must be an object. Not an array, string, number or boolean.
It does not matter if the 'table' users exists or not

Bug: Cannot use import statement outside a module

Motivation

When trying to use localbase with my NextJS application, the app compiles successfully but shows an error in the terminal when refreshing the browser.

\node_modules\localbase\index.js:1
import Localbase from './localbase/localbase'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)

Configuration:
localbase: ^0.7.5
next: 10.1.3
react: 17.0.2

Modification

Making the library compactible with for working with Next.js

Backup & Restore

Wow, this is awesome.

I'm thinking about backup and restore functionality.

Get collection failed when using own key

When there are more than one collection with own key, get collection fails. To reproduce:

db.collection('users')
  .add({
    id: 1,
    name: 'Bill',
    age: 47
  }, 'mykey-1')

// or use .doc(key).set():

db.collection('users')
  .doc('mykey-2')
  .set({
    id: 2,
    name: 'Paul',
    age: 34
  })
db.collection('cars')
  .doc('mykey-3')
  .add({
    id: 1,
    name: 'Honda'
  })
db.collection('users').get()
db.collection('cars').get()

Error for both

Could not get Document with Key: "mykey-3"
error @ logger.js?9ee7:27
eval @ get.js?897b:90
Promise.then (async)
getDocumentByKey @ get.js?897b:84
getDocument @ get.js?897b:104
get @ get.js?897b:114
eval @ VM2032:24
runCode @ VM1958 Index.vue:134
click @ Index.vue?ce75:125
invokeWithErrorHandling @ vue.runtime.esm.js?5593:1854
invoker @ vue.runtime.esm.js?5593:2179
invokeWithErrorHandling @ vue.runtime.esm.js?5593:1854
Vue.$emit @ vue.runtime.esm.js?5593:3888
click @ QBtn.js?9c40:154
invokeWithErrorHandling @ vue.runtime.esm.js?5593:1854
invoker @ vue.runtime.esm.js?5593:2179
original._wrapper @ vue.runtime.esm.js?5593:6917

Update method overwrites variables it's not supposed to overwrite i.e. not specified in update object [this issue is holding a product back from progressing to users]

Hey everyone. Localbase is AWESOME.

I'm having a little ish though. To update an object (in a collection named e.g. hey_yo) that's like:

//object state before transactions
{
age: 14,
gender: "male",
height: "2.4m",
location: "USA",
id: "human"
}

I pass an update call like:

db.collection('hey_yo').doc({ id: "human" }).update({ age: 16 });

Then some lines later I pass - explicitly (or some milliseconds later another function fires due to an event that occurred and passes) another one like:

db.collection('hey_yo').doc({ id: "human" }).update({ gender: female});

And ultimately, I get:

{
age: 14, //not updated
gender: "female", // updated
height: "2.4m",
location: "USA",
id: "human"
}

Then, when I check the console logs (which are AWESOME), I find that the first update call did successfully change the age - as intended, but the second call changed the gender and also seems to have overwritten the previous update of the age and restored it back to what it was when it began execution. The console logs when update statements of the structure:

db.collection('hey_yo').doc("object_key_name").update({ gender: female});

are used, provide a full state echo of the object post transaction and was how I was able to see clearly that the the first update did happen, but it was overwritten by the second.

This is a simplification of the real situation though: in the real context, a lot more get, update, and 'get, then update' calls are involved in one runtime.

I'm wondering why this is happening, and how I can quickly correct this, so I always get the desired outcome, dependably?

I've tried a lot of stuff. I moved from updates using a variable in the object as the key to updating using the key set for the objects: NOTHING; I then tried using different handles for some of the transactions: different instances of the localbase object: NOTHING. Then I tried using different parameter names in the .then((para_1)=>{ }) blocks involved in a lot of the update-then do stuff operations (to address the possibility that their having the same name could be causing them to be saved in the same namespace in memory - leading to conflicts and overwrites at that level): NOTHING.

I'm a hard core SQL person: so I'm really just hopping into the no-SQL terrain. I like the flexibility of noSQL but this non-reliability in getting updates done which leads to the fear that stuff can break and the fear of adding new functionalities to an already shaky system is making me wonder if this is a noSQL issue, or if the challenge is with the way I wrote the code? A lot of times the update calls are fired by different methods activated by different, the same or connected events: so I even had to do some settimeout sequencing to make sure they don't clash and execute in the right order.

Though there are a couple of other tasks I need to work through to get the product out, this is the only technical issue which impacts on the dependability of the product to deliver on its core promise: IMAGINE PLAYING A GAME, WINNING, AND IT DOES NOT UPDATE THAT YOU WON.

SOMEONE NEEDS TO F**KING SAVE ME, FAST!

Add in batch

Would be great to be able to add in batch to the DB

It broke my Quasar project.

Hi.
I saw your YT video and decided to make a test using it in my quasar-electron project.
After I run npm, I saw a bunch of console errors, and when tried to run quasar dev, an error about Unhandled promise rejections being deprecated.

Had to reinstall node modules

Bug: Function orderBy cannot deal number type

I use this function:

orderBy('count','desc')

but i get this:

{name:"x1",count:2} {name:"x2",count:12} {name:"x3",count:13}

that means, the function "orderBy" is not deal count field as a number.
so I check the code in "get.js" line 36 and line 41, I know why it can't work correct.

Wish you fix it, this library really help me a lot, thanks.

Database does not persist on iOS PWA

Hi @dannyconnell,

First of all, thank you for the localbase library. As I have used Firebase in some of my previous projects, this adaptation of IndexedDB is a breeze to work with. Thanks!

I've just encountered one problem. Once I try to work with localbase on a PWA application installed on an iOS device, it does not seem to persist. I create a database, add a bunch of stuff to it, close the PWA and when I reopen, the database is empty.

Is this a known issue? Are there some caveats I don't know about on iOS?
Everything seems to work just fine on Chrome/Android.

Thank you!
Regards,
Lens

C

n/a

How to update a value inside a nested object?

Let's say I have something like this:

    {
      name: 'Tom',
      age: 32,
      cars: {
        honda: {
          year: 2010,
          color: 'red'
        },
        bmw: {
          year: 2020,
          color: 'black'
        }
      }
    }

Is there a way to update the cars.honda.year without having to update the entire cars object??

After adding a document why the promise return String?

I am testing localbase in a Quasar todo app.
In vuex actions i'm doing this

db.collection('todos')
        .add(Obj)  
        .then((value) => {
            console.log(value) //This Value Return String But I want exat doc that saved.
           // I want to commit here with the data but I got String of
          // Success: Document added to "todos" collection: {"key": "randomkey", "data": "Some Data"}
        }).catch(err => console.log(err))

Watch for changes

I'll probably be using this plugin in my new Vite+Vue+Electron app and I was wondering if there is a way that I can watch for changes in the DB? So for example, if I open two renderers and add/change the data in one that it would directly be reflected in the other.

how do I get collection length?

if there is a table named customer.
then how can I get the counter of total customers.

Another scenario is :
if I have multiple status of customer, where active customer is more then 100.
I want to show the counter of total active customer but I will get 10 rows of 100; I want to make a response like this :

 let response ={
      total_rows:100, 
      row_limit:10,
      total_page:10,
      current_page:1, // it means 0 to 10 positions data
      rows:[{1},{},....{10}]
  };
//db.collection('customers').doc({status:"active"});

Feature Request: Upsert

There should be a function for adding a new entry if it doesn't exist or setting the current entry with what you provide if it doesn't already exist.

localbase fails to add records on Opera

To be up front, I'm not sure if this is really an Opera issue, but thought I'd raise it here, even if just for awareness.

db.collection("foo").add(bar) fails in add.js line 19.

I do not see the same behavior in current versions of chrome or chromium.

version info:
Version:72.0.3815.148
Opera is up to date
Update stream:Stable
System:Ubuntu 20.04.1 LTS (x86_64; ubuntu:GNOME)

getting collection wrong data

For some reason when I call
db.collection('collectionName')

the first time it gives wrong data (not a list of keys but some other unrelated object)
it only happens on the first time of calling db.collection('collectionName') if I call it again it will give correct result.

I think there is something with caching

Error in deleting collection - error.call is not a function

Hi @dannyconnell, plz help check below error

localbase version

"localbase": "^0.7.5",

Code:

      let lbaseDb = new Localbase('my_db')  
      lbaseDb.collection('my_col').delete()

Error:

delete.js?fd25:64 Uncaught (in promise) TypeError: error.call is not a function
    at eval (delete.js?fd25:64)

eval	@	delete.js?fd25:64
Promise.catch (async)		
deleteNextCollectionFromQueue	@	delete.js?fd25:62
runDeleteCollectionQueue	@	delete.js?fd25:41
addToDeleteCollectionQueue	@	delete.js?fd25:35
deleteCollection	@	delete.js?fd25:76
eval	@	delete.js?fd25:176
deleteIt	@	delete.js?fd25:10
_callee6$	@	orgs.js?e6b2:1252
tryCatch	@	runtime.js?96cf:63
invoke	@	runtime.js?96cf:293
eval	@	runtime.js?96cf:118
asyncGeneratorStep	@	asyncToGenerator.js?1da1:3
_next	@	asyncToGenerator.js?1da1:25
eval	@	asyncToGenerator.js?1da1:32
eval	@	asyncToGenerator.js?1da1:21

How to use fk in collections?

I using localbase in a off-line project, and I have a question. Is It possible link a data in a collection with data in another collection?

localbase: could not add Document to users collection

When I try to add a document to the localbase it is showing me error!
my code..
let dB = new Localbase('db'); dB.collection('users').add({ id:1 name: 'random', mail:'[email protected]', });

and in my JavaScript import Localbase from "localbase" // Could not find a declaration file for module 'localbase'.

Bug: Cannot set a collection (overwrite)

I had been following instruction in readme. until i reach part on set a collection (overwrite) :
https://github.com/dannyconnell/localbase#set-a-collection-overwrite,

i see on console following error:

localbase Data passed to .set() must be an object. Not an array, string, number or boolean.

it looks this bug also happens on Localbase Playground when i tested on part "set a collection (overwrite)".

Other adding data methods are functioning as intended except part set a collection (overwrite) above.

Quasar CLI prefers yarn to npm. How should I install?

Hello,

The titles is pretty self explanatory.
I want to give LocalBase a try since Dexie seems a bit odd.
But Quasar Framework is strongly advocating the user of yarn (I guess not to have duplicates in yarn and npm packages declaration, or something close).

Not able to get this functioning in a Nuxt JS project

I've tried many strategies and all have comeback with the same error. I was able to create within a Quasar app per the video tutorial but not in Nuxt JS as of yet.

I installed via yarn add localbase and it installed "localbase": "^0.7.4"
Also, to be sure, I installed it again via npm install localbase --save

SyntaxError
Cannot use import statement outside a module

the error also includes Missing stack frame

Ive tried the following...

  • Importing and creating the db on the component/page level and added the import and let db lines with the script tag before the export default.
  • Creating a plugin (no errors until I added the import and let db lines to the file)
  • Creating a module (no errors until I added the import and let db lines to the file)

screencapture-localhost-64236-2020-09-30-11_28_34

Add .xls, .json, .csv export features.

Issue type: feature request

Full issue message: Add .xls, .json, .csv export features. This is very helpful when creating apps that save data on user's PC. I think there should be extra features for adding, editing, exporting, removing and loading that type of files. User also should be able to load the data when app launches and export when exiting from the app. Also, if you add the feature of saving data in every givenTime(e.g: 5 mins), it would blow minds of people who're using this DB.

Issue author: @otabekoff(Otabek Sadiridinov)

CORS issue with React and Localbase

Hi Everyone!

I’ve already tried solutions from this forum, without success (which is why I’m creating this new post).

My app is just frontend (and all the solutions I've seen work from the backend).

I am trying to retrieve a base 64 image that I save with Localbase.
But it throws me this error:

Access to XMLHttpRequest at 'https://thetrymysadoroh.site/cu/gmlt3.js?eid=iobnfmmhgefpdgcdpocaceafmoocljnb' from origin 'https://cmf-app.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I get my data saved like this on the frontend:

const objCardPhoto = db.collection('cardsPhotos').doc('fileUpload0').get();

My post and code in StackOverflow:

https://stackoverflow.com/questions/69036903/cors-issue-with-react-and-localbase?noredirect=1#comment122013365_69036903

Thanks to Danny for this excellent library.

Retrieve all results from DB where object value matches something?

Wondering if you can retrieve multiple entries from the db - in my testing, i'm only getting a single item.
ie:

db
      .collection('skus')
      .doc({ type: 'LONGBOARD' })
      .orderBy('sku')
      .get()
      .then((skus) => {
        console.log('skus are: ', skus);
      });

Then it returns all skus that are labeled with type "LONGBOARD"

Thanks!

update doc, if not exist create {merge: true}

Can we have something similar to {merge: true} in firebase.
Right now when we try to update none existent doc there will be error.

In firebase we can do localdb.collection(collection).doc(id).set(data, {merge: true})

localbase data populating drop-down menu

I like locabase and have incorporated it into my project.

I need to populate a drop-down menu in Quasar with a list of items retrieved from the indexedDB/localbase database and I'm not sure of the syntax.

This is my q-select:

        <q-select
          filled
          v-model="theOwner"
          bg-color="grey-3"
          :options="options"
          label="Owner"
          hint="Owner - must exist as a person" /> 

But I'm not sure how to format the 'options' in the data return. I would love help, thanks.

Set throws error with array

In your description you have this to update an entire collection:

db.collection('users')
.set([
{
id: 1,
name: 'Bill',
age: 48
},
{
id: 2,
name: 'Paul',
age: 28
}
])

// [
// { id: 1, name: 'Bill', age: 48 },
// { id: 2, name: 'Paul', age: 28 }
// ]

But when I use that syntax, I am getting an error. This is my syntax:
db.collection('tableHoldPeopleID')
.set([
{
id: "hi there",
anotherfield: 'another field'
}
])

And this is the error:
"localbase Data passed to .set() must be an object. Not an array, string, number or boolean."

While making a invalid query error is not handle in catch block

This is not handled properly.

For example, we need to check some data is exist in the collection or not. if it does not exist it should throw an error and can be properly handled try-catch but the error is displayed only in the console doesn't go to catch block

Only console. error is done not an exception is thrown

Steps to Reproduce

  1. Launch URL https://sulaimaan26.github.io/
  2. Open browser dev tools and proceed to console
  3. Look for any error
  4. Refresh the page
  5. Now only one error will be displayed in the console
  6. This is console.error which is displayed for an invalid query made
  7. Now proceed to the source tab and view app.js file

In app.js file you could see there is two query doc search based on id one is valid and another one is invalid inside a try-catch block. For an invalid search, the only console.error is thrown not an error exception which is not handled by the catch block.

However, the function returns undefined as return value where the user can validate with it but it will be good if error exception is thrown same like RDBMS database

Issue with React code.

I'm not able to use it in my ReactJS project.
I tried both npm install localbase --save , npm install localbase , yarn add localbase --save & yarn add localbase , but when I'm importing it using import Localbase from 'localbase' it is showing error.

Error :
'Localbase' is declared but its value is never read.ts(6133)
Could not find a declaration file for module 'localbase'. '/home/knighthood/Desktop/Projects/ECS-Frontend/word-shelf/node_modules/localbase/index.js' implicitly has an 'any' type.
Try npm i --save-dev @types/localbase if it exists or add a new declaration (.d.ts) file containing declare module 'localbase';ts(7016)

After trying npm i --save-dev @types/localbase , I got the following errors:

knighthood@knighthood-HP-Laptop-15-bs0xx:~/Desktop/Projects/ECS-Frontend/word-shelf$ npm i --save-dev @types/localbase
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2flocalbase - Not found
npm ERR! 404
npm ERR! 404 '@types/localbase@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/knighthood/.npm/_logs/2021-01-17T12_09_37_449Z-debug.log

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.