Git Product home page Git Product logo

redux-persist-idb-storage's Introduction

Redux Persist adapter for IndexedDB storage

Storage adapter to use IndexedDB via idb v3 with redux-persist ripped from idb v3 docs > Examples section

Installation

Using npm:

npm install --save @piotr-cz/redux-persist-idb-storage

or Yarn:

yarn add @piotr-cz/redux-persist-idb-storage

Requirements

Setup

Import the storage and include it in persistConfig when creating Redux store:

// configureStore.js

import createIdbStorage from '@piotr-cz/redux-persist-idb-storage'

const persistConfig = {
  key: 'root',
  storage: createIdbStorage({name: 'myApp', storeName: 'keyval'}),
  serialize: false, // Data serialization is not required and disabling it allows you to inspect storage value in DevTools; Available since [email protected]
  deserialize: false, // Required to bear same value as `serialize` since [email protected]
}

// ...

Server-Side Rendering

When using Server-Side Rendering (SSR), indexedDB won't be available in the environment.

In this case you may use feature detection with a fallback to use default redux-persist storage (which resolves to noop functions):

// configureStore.js

// Redux Persist storage
import defaultStorage from 'redux-persist/lib/storage'

// IndexedDB storage
import createIdbStorage from '@piotr-cz/redux-persist-idb-storage/src'

const persistConfig = {
  key: 'root',
  storage: globalThis.indexedDB ? createIdbStorage({name: 'myApp', storeName: 'keyval'}) : defaultStorage,
  serialize: false, 
}

Options

See idb API

  • name (optional): IndexedDB Database name. Defaults to 'keyval-store'.
  • storeName (optional): IndexedDB Store name. Defaults to 'keyval'.
  • version (optional): Schema version. Defaults to 1.
  • upgradeCallback (optional): Defaults to upgradeDb => upgradeDb.createObjectStore(options.storeName).

Notes

  • idb dependency is locked to version ^3.0.0 as 4+ uses proxies which are not supported in older browsers
  • credits go to idb authors

redux-persist-idb-storage's People

Contributors

dependabot[bot] avatar mxsxs2 avatar piotr-cz avatar

Stargazers

 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

redux-persist-idb-storage's Issues

Fantastic work

I know this isn't an issue, but I've been searching far and wide for something to resolve the fact that redux-persist can get REALLY expensive with all the serialization. This was so easy to set up and works a dream.

Thanks so much.

Create react app Unexpected token in ./node_modules/source-map-loader/dist/cjs.js

Hi,
I have application via create-react-app in redux template and when i use yours library it throws me this error:

 Starting the development server...
redux_container  |
redux_container  | Failed to compile.
redux_container  |
redux_container  | Module parse failed: Unexpected token (13:16)
redux_container  | File was processed with these loaders:
redux_container  |  * ./node_modules/source-map-loader/dist/cjs.js
redux_container  | You may need an additional loader to handle the result of these loaders.
redux_container  | |
redux_container  | | export default function createIdbStorage(
redux_container  | >   definedOptions: {
redux_container  | |     name?: string
redux_container  | |     storeName?: string
redux_container  | ERROR in ./node_modules/@piotr-cz/redux-persist-idb-storage/src/index.ts 13:16
redux_container  | Module parse failed: Unexpected token (13:16)
redux_container  | File was processed with these loaders:
redux_container  |  * ./node_modules/source-map-loader/dist/cjs.js
redux_container  | You may need an additional loader to handle the result of these loaders.
redux_container  | |
redux_container  | | export default function createIdbStorage(
redux_container  | >   definedOptions: {
redux_container  | |     name?: string
redux_container  | |     storeName?: string
redux_container  |
redux_container  | webpack compiled with 1 error
redux_container  | Files successfully emitted, waiting for typecheck results...
redux_container  | Issues checking in progress...
redux_container  | No issues found.

when i use in .env:

GENERATE_SOURCEMAP=false

error message is different:

redux_container  | Starting the development server...
redux_container  |
redux_container  | Failed to compile.
redux_container  |
redux_container  | Module parse failed: Unexpected token (13:16)
redux_container  | You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
redux_container  | |
redux_container  | | export default function createIdbStorage(
redux_container  | >   definedOptions: {
redux_container  | |     name?: string
redux_container  | |     storeName?: string
redux_container  | ERROR in ./node_modules/@piotr-cz/redux-persist-idb-storage/src/index.ts 13:16
redux_container  | Module parse failed: Unexpected token (13:16)
redux_container  | You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
redux_container  | |
redux_container  | | export default function createIdbStorage(
redux_container  | >   definedOptions: {
redux_container  | |     name?: string
redux_container  | |     storeName?: string
redux_container  |
redux_container  | webpack compiled with 1 error

i use [email protected]

Could you please help me?
Thanks

`getAll` doesn't need a `readwrite` lock

getAll can be readonly here:
https://github.com/piotr-cz/redux-persist-idb-storage/blob/master/src/index.ts#L112

I would have PR'd just this fix, but I ended up forking away from the library because I wanted idb v6 and didn't think that'd be accepted because the v3 dep is considered a feature in the readme. Anyway, here's my v6 impl which inherently fixes the above. I'm happy to PR it if you like.

/**
 * Thin wrapper around idb to use as redux-persist storage using single object store for all data
 * @see https://github.com/jakearchibald/idb
 *
 * Based on https://github.com/piotr-cz/redux-persist-idb-storage, but upgraded to idb 6
 * and fixed a perf bug.
 */
import { openDB } from 'idb'

interface Options {
  name: string
  storeName: string
  version: number
}

const defaultOptions: Options = {
  name: 'keyval-store',
  storeName: 'keyval',
  version: 1
}

export default function createIdbStorage (options: Options = defaultOptions) {
  const dbPromise = openDB(options.name, options.version, {
    upgrade (db) {
      db.createObjectStore(options.storeName)
    }
  })

  return {
    async getItem (key: string) {
      return (await dbPromise).get(options.storeName, key)
    },

    async setItem (key: string, item: IDBValidKey) {
      return (await dbPromise).put(options.storeName, item, key)
    },

    async removeItem (key: string) {
      return (await dbPromise).delete(options.storeName, key)
    },

    async getAllKeys () {
      return (await dbPromise).getAllKeys(options.storeName)
    },

    async getAll () {
      return (await dbPromise).getAll(options.storeName)
    },

    async clear () {
      return (await dbPromise).clear(options.storeName)
    }
  }
}

Swap in reduxjs-toolkit-persist?

AFAIK reduxjs-toolkit-persist was forked from redux-persist, but do you have any objections or see any obstacles to switching to the reduxjs-toolkit's fork?

Error restoring data [object Object]

Reported by @bigfree:

I try, build is success but now there is an error in retrieving data from the DB ๐Ÿ˜ข

redux-persist/getStoredState: Error restoring data [object Object] SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at defaultDeserialize (getStoredState.js:39:1)
    at getStoredState.js:23:1

The data is stored in the database, but when the page is refreshed, it is no longer in the database. However, the structure of the database remains the same.

Store data:
image

After refresh:
image

My persist config:

const persistConfig: PersistConfig<any> = {
    key: 'root',
    version: 1,
    storage: createIdbStorage({
        name: 'craedit',
        storeName: 'craeditstore',
        version: 1
    }),
    timeout: 100,
    serialize: false,
    debug: true,
    blacklist: ['point']
};

Originally posted by @bigfree in #14 (comment)

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.