Giter Club home page Giter Club logo

localforage-observable's Introduction

localForage

NPM version npm jsDelivr Hits minzipped size

localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asynchronous storage (IndexedDB or WebSQL) with a simple, localStorage-like API.

localForage uses localStorage in browsers with no IndexedDB or WebSQL support. See the wiki for detailed compatibility info.

To use localForage, just drop a single JavaScript file into your page:

<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>

Try the live example.

Download the latest localForage from GitHub, or install with npm:

npm install localforage

Support

Lost? Need help? Try the localForage API documentation. localForage API文档也有中文版。

If you're having trouble using the library, running the tests, or want to contribute to localForage, please look through the existing issues for your problem first before creating a new one. If you still need help, feel free to file an issue.

How to use localForage

Callbacks vs Promises

Because localForage uses async storage, it has an async API. It's otherwise exactly the same as the localStorage API.

localForage has a dual API that allows you to either use Node-style callbacks or Promises. If you are unsure which one is right for you, it's recommended to use Promises.

Here's an example of the Node-style callback form:

localforage.setItem('key', 'value', function (err) {
  // if err is non-null, we got an error
  localforage.getItem('key', function (err, value) {
    // if err is non-null, we got an error. otherwise, value is the value
  });
});

And the Promise form:

localforage.setItem('key', 'value').then(function () {
  return localforage.getItem('key');
}).then(function (value) {
  // we got our value
}).catch(function (err) {
  // we got an error
});

Or, use async/await:

try {
    const value = await localforage.getItem('somekey');
    // This code runs once the value has been loaded
    // from the offline store.
    console.log(value);
} catch (err) {
    // This code runs if there were any errors.
    console.log(err);
}

For more examples, please visit the API docs.

Storing Blobs, TypedArrays, and other JS objects

You can store any type in localForage; you aren't limited to strings like in localStorage. Even if localStorage is your storage backend, localForage automatically does JSON.parse() and JSON.stringify() when getting/setting values.

localForage supports storing all native JS objects that can be serialized to JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the API docs for a full list of types supported by localForage.

All types are supported in every storage backend, though storage limits in localStorage make storing many large Blobs impossible.

Configuration

You can set database information with the config() method. Available options are driver, name, storeName, version, size, and description.

Example:

localforage.config({
    driver      : localforage.WEBSQL, // Force WebSQL; same as using setDriver()
    name        : 'myApp',
    version     : 1.0,
    size        : 4980736, // Size of database, in bytes. WebSQL-only for now.
    storeName   : 'keyvaluepairs', // Should be alphanumeric, with underscores.
    description : 'some description'
});

Note: you must call config() before you interact with your data. This means calling config() before using getItem(), setItem(), removeItem(), clear(), key(), keys() or length().

Multiple instances

You can create multiple instances of localForage that point to different stores using createInstance. All the configuration options used by config are supported.

var store = localforage.createInstance({
  name: "nameHere"
});

var otherStore = localforage.createInstance({
  name: "otherName"
});

// Setting the key on one of these doesn't affect the other.
store.setItem("key", "value");
otherStore.setItem("key", "value2");

RequireJS

You can use localForage with RequireJS:

define(['localforage'], function(localforage) {
    // As a callback:
    localforage.setItem('mykey', 'myvalue', console.log);

    // With a Promise:
    localforage.setItem('mykey', 'myvalue').then(console.log);
});

TypeScript

If you have the allowSyntheticDefaultImports compiler option set to true in your tsconfig.json (supported in TypeScript v1.8+), you should use:

import localForage from "localforage";

Otherwise you should use one of the following:

import * as localForage from "localforage";
// or, in case that the typescript version that you are using
// doesn't support ES6 style imports for UMD modules like localForage
import localForage = require("localforage");

Framework Support

If you use a framework listed, there's a localForage storage driver for the models in your framework so you can store data offline with localForage. We have drivers for the following frameworks:

If you have a driver you'd like listed, please open an issue to have it added to this list.

Custom Drivers

You can create your own driver if you want; see the defineDriver API docs.

There is a list of custom drivers on the wiki.

Working on localForage

You'll need node/npm and bower.

To work on localForage, you should start by forking it and installing its dependencies. Replace USERNAME with your GitHub username and run the following:

# Install bower globally if you don't have it:
npm install -g bower

# Replace USERNAME with your GitHub username:
git clone [email protected]:USERNAME/localForage.git
cd localForage
npm install
bower install

Omitting the bower dependencies will cause the tests to fail!

Running Tests

You need PhantomJS installed to run local tests. Run npm test (or, directly: grunt test). Your code must also pass the linter.

localForage is designed to run in the browser, so the tests explicitly require a browser environment. Local tests are run on a headless WebKit (using PhantomJS).

When you submit a pull request, tests will be run against all browsers that localForage supports on Travis CI using Sauce Labs.

Library Size

As of version 1.7.3 the payload added to your app is rather small. Served using gzip compression, localForage will add less than 10k to your total bundle size:

minified
`~29kB`
gzipped
`~8.8kB`
brotli'd
`~7.8kB`

License

This program is free software; it is distributed under an Apache License.


Copyright (c) 2013-2016 Mozilla (Contributors).

localforage-observable's People

Contributors

danmaas avatar neelabhg avatar thgreasi avatar tofumatt avatar waynebrantley 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

Watchers

 avatar  avatar  avatar  avatar  avatar

localforage-observable's Issues

Use LocalForage-observable in an es6/typescript environment

I'd like to use localforage-observable in a typescript project (Angular2). What is the correct way to import and use it using es6 modules? For example, I can use localforage in a module by importing it:

import * as localforage from 'localforage';

Localforage-observable just extends localforage, but I can't figure out how to include it and extend localforage. I've tried each of the following to no avail (including the above statement every time):

import * as lo from 'localforage-observable';
import 'localforage-observable';
require('localforage-observable');
const lo = require('localforage-observable');

None of those work. Can you point me in the right direction?

Observable is not defined error while trying localForage.newObservable({})

I'm working on [email protected] with [email protected] and localforage-observable@^2.1.1

Just following the same steps as in documentation, but getting error in localforage.newObservable(). Tried with different versions of localforage-observable also, but nothing works

import localForage from "localforage";
// OR based on your configuration:
// import * as localForage from "localforage";

import { extendPrototype } from "localforage-observable";

var localforage = extendPrototype(localForage);
localforage.ready().then(() => {
  // TypeScript will find `newObservable()` after the casting that `extendPrototype()` does
  var observable = localforage.newObservable();
});

Following error while running application:

Unhandled Promise rejection: Observable is not defined ; Zone: <root> ; Task: Promise.then ; Value: ReferenceError: Observable is not defined
    at newObservable.factory (localforage-observable.js:444:9)
    at LocalForage.newObservable (localforage-observable.js:431:40)

ReferenceError: Observable is not defined

I have converted my app to use the new corejs as babel/polyfill is deprecated. https://babeljs.io/docs/en/babel-polyfill

When I remove babel-polyfill from my webpack:

        entry: {
            'main-client': [
                "babel-polyfill",
                'react-hot-loader/patch',
                './clientApp/boot-client.tsx'
            ]
        },

It causes Observable is not defined. (and this is on latest version of chrome that does not need any polyfills).
Uncaught (in promise) ReferenceError: Observable is not defined
at Function.newObservable.factory (localforage-observable.js:443)
at LocalForage.newObservable (localforage-observable.js:430)

I put the babel-polyfill back and it works just fine. Any thoughts - I noticed your zen dependency is pretty far behind, but not sure if that will fix it?

ReferenceError: Observable is not defined

Hi,

I've installed this library's v1.4.0 and I'm getting this error ("ReferenceError: Observable is not defined"). I've tried to use it like this:

import * as localforage from "localforage";
import "localforage-observable";

[...]

  componentDidMount = () => {
    localforage.ready(() => {
      const observable = localforage.newObservable({ key: "Messages" });
      this.subscription = observable.subscribe({
        next: data => {
          // handle data changes
        }
      });
    });
  };

But I always get the error and I don't know which could be the error.

I've checked the examples (https://codepen.io/thgreasi/pen/LNKZxQ) and the error appears too.

Thanks!

[Question] Observe this same store from different instances

Hi, there is a way to observe this same store and detect "cross" changes from two different instances? I was able to only detect changes made from this same instance.

const instanceOne = localforage.createInstance({
    name        : dbName,
    storeName   : 'tableOne',
});

const instanceTwo = localforage.createInstance({
    name        : dbName,
    storeName   : 'tableOne',
});

...

const observableOne = instanceOne.newObservable()
const subscriptionOne = observableOne.subscribe({ next: (args) => { ... } })

...

const observableTwo = instanceTwo.newObservable()
const subscriptionTwo = observableTwo.subscribe({ next: (args) => { ... } })

...
 
instanceOne.setItem("ACTION", { value: "something" }) // it should be caught by both observable
 

clear() doesn't trigger event

Using the code below, i don't seem to get an event for the localforage.clear() method.

import localforage from 'localforage'
import 'localforage-observable'

let store = localforage.createInstance({name:'clear-test'})
store.ready(function() {
  let observable = store.newObservable({
  })
  observable.subscribe({
    next: function(args) {
      console.log('observable', args);
    }
  })
})

store.setItem('1','test')
.then(()=>{store.clear()})

I do get an event on the setItem() method.
The 'clear-test' database is emtpy afterward, so the clear() method worked.

Tested on FF 58.0.2 and IE 11.248
localforage: 1.5.3 and 1.6.0
localforage-observable: 1.4.0

I'm interested in what this adds to localForage's promise based api?

Really well documented project btw. The API definition in typescript is a nice idea I wish other people would follow.

I'm interested in the value of this project though.

Is it just converting a localforage promise to a one shot observable?
If so a generic function to convert promise to one shot observables like RxJS Rx.Observable.fromPromise() should be used in a project.

localforage.setItem in a promise won't fire Observable with rxjs

So I have this method which pulls user data from the server and then caches it via localforage. When I set the data in a promise the Observable isn't fired.

UserCacheProxy

public getUsers(userIds: string[], callback: NextObserver<any> | Function) {
    let cacheKeys = userIds.map((userId:any) => {
        return this.getUserCacheKey(userId);
    });

    let applyCallback = (item) => {
        this.$rootScope.$apply(() => {
            callback(item);
        });
    };

    //noinspection TypeScriptUnresolvedFunction
    let subscriber = Observable.from(cacheKeys)
        .flatMap((key) => {
            this.CacheService.getItem(key)
                .then((user: IApiUser) => {
                    return new ngLeague.User(user);
                })
                .then(applyCallback)
                .catch(x => x);

            return this.CacheService.getObservable(key);
        })
        .map((user:IApiUser) => {
            console.log(user);
            return new ngLeague.User(user);
        })
        .subscribe(applyCallback);

    this.CacheService.setItem("user:9373305", "Hi", this.CachingTimes.getUserCacheTimeout());

    this.fetchUncachedUsers(userIds).then((users) => {
        this.CacheService.setItem("user:9373305", "Hi2", this.CachingTimes.getUserCacheTimeout());

        _.forEach(users, (user: IApiUser) => {
            let cacheKey = this.getUserCacheKey(user.id);
            this.CacheService.setItem(cacheKey, user);
        });
    });

    return subscriber;
}

Which I call like that:

UserCacheProxy.getUsers(["9373305"], function(user:ngLeague.User) {
    // do nothing
});

Expected result:

User {apiData: "Hi"}
User {apiData: "Hi2"}
User {apiData: "{..}"} // actual user data from the server

Actual result:

User {apiData: "Hi"}

Note:

  • Also happens without the $rootScope.$apply from angular
  • Doesn't matter if item already exists in the database or not

Support for localforage instances

Would you consider adding support for localforage instances?
Are there big problems to solve for it?
Is there a workaround I can use to support it now?

How to merge multiple observables in to one?

I've tried the following

CacheService.ts

public getObservable(key) {
        return this.localForage.newObservable({key: key}).map((item:any) => {
            return this.getItemContent(key, item);
        });
}

Doesn't fire the subscribe methods

return Observable.from(teamIds).flatMap((teamId:any) => {
    return this.CacheService.getObservable(this.getTeamCacheKey(teamId));
});

Doesn't fire the subscribe methods either

let observables = teamIds.map((teamId:any) => {
    return this.CacheService.getObservable(this.getTeamCacheKey(teamId));
});

//noinspection TypeScriptUnresolvedFunction
return Observable.concat(observables).flatMap((x:any) => {
    return x;
});

note: When I use .map instead of .flatMap it works, but it returns the single Observables which I do not want :)

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.