{"id":4690,"url":"https://github.com/sunnylqm/react-native-storage","last_synced_at":"2025-05-14T02:04:58.025Z","repository":{"id":35504198,"uuid":"39774073","full_name":"sunnylqm/react-native-storage","owner":"sunnylqm","description":"local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.","archived":false,"fork":false,"pushed_at":"2024-03-03T12:49:50.000Z","size":1085,"stargazers_count":3034,"open_issues_count":24,"forks_count":267,"subscribers_count":45,"default_branch":"master","last_synced_at":"2025-05-11T12:04:43.611Z","etag":null,"topics":["asyncstorage","localstorage","react-native","reactjs","sync"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sunnylqm.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2015-07-27T12:49:29.000Z","updated_at":"2025-05-10T16:37:59.000Z","dependencies_parsed_at":"2024-03-18T00:23:58.784Z","dependency_job_id":"075b8601-ada7-4a6d-a1da-5cbf90bc9cfb","html_url":"https://github.com/sunnylqm/react-native-storage","commit_stats":{"total_commits":136,"total_committers":25,"mean_commits":5.44,"dds":"0.30147058823529416","last_synced_commit":"96df43f0028a6afd08bc56e80d327fabb5fff583"},"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sunnylqm%2Freact-native-storage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sunnylqm%2Freact-native-storage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sunnylqm%2Freact-native-storage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sunnylqm%2Freact-native-storage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sunnylqm","download_url":"https://codeload.github.com/sunnylqm/react-native-storage/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253838078,"owners_count":21972090,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncstorage","localstorage","react-native","reactjs","sync"],"created_at":"2024-01-05T20:17:20.384Z","updated_at":"2025-05-14T02:04:57.980Z","avatar_url":"https://github.com/sunnylqm.png","language":"JavaScript","readme":"# react-native-storage [![Backers on Open Collective](https://opencollective.com/react-native-storage/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/react-native-storage/sponsors/badge.svg)](#sponsors) [![Build Status](https://travis-ci.org/sunnylqm/react-native-storage.svg)](https://travis-ci.org/sunnylqm/react-native-storage) ![npm version](https://img.shields.io/npm/v/react-native-storage.svg)\n\nThis is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). [ES6](http://babeljs.io/docs/learn-es2015/) syntax, promise for async load, fully tested with jest.\n\n查看中文文档[请点击 README-CHN.md](README.zh-CN.md)\n\n## Install\n\n```\nnpm install react-native-storage\nnpm install @react-native-async-storage/async-storage\n```\n\nor\n\n```\nyarn add react-native-storage\nyarn add @react-native-async-storage/async-storage\n```\n\n## Usage\n\n### Init\n\n```js\nimport Storage from 'react-native-storage';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\n\nconst storage = new Storage({\n  // maximum capacity, default 1000 key-ids\n  size: 1000,\n\n  // Use AsyncStorage for RN apps, or window.localStorage for web apps.\n  // If storageBackend is not set, data will be lost after reload.\n  storageBackend: AsyncStorage, // for web: window.localStorage\n\n  // expire time, default: 1 day (1000 * 3600 * 24 milliseconds).\n  // can be null, which means never expire.\n  defaultExpires: 1000 * 3600 * 24,\n\n  // cache data in the memory. default is true.\n  enableCache: true,\n\n  // if data was not found in storage or expired data was found,\n  // the corresponding sync method will be invoked returning\n  // the latest data.\n  sync: {\n    // we'll talk about the details later.\n  }\n});\n\nexport default storage;\n```\n\n### Save \u0026 Load \u0026 Remove\n\n```js\n// Save something with key only. (using only a keyname but no id)\n// This key should be unique. This is for data frequently used.\n// The key and value pair is permanently stored unless you remove it yourself.\nstorage.save({\n  key: 'loginState', // Note: Do not use underscore(\"_\") in key!\n  data: {\n    from: 'some other site',\n    userid: 'some userid',\n    token: 'some token'\n  },\n\n  // if expires not specified, the defaultExpires will be applied instead.\n  // if set to null, then it will never expire.\n  expires: 1000 * 3600\n});\n\n// load\nstorage\n  .load({\n    key: 'loginState',\n\n    // autoSync (default: true) means if data is not found or has expired,\n    // then invoke the corresponding sync method\n    autoSync: true,\n\n    // syncInBackground (default: true) means if data expired,\n    // return the outdated data first while invoking the sync method.\n    // If syncInBackground is set to false, and there is expired data,\n    // it will wait for the new data and return only after the sync completed.\n    // (This, of course, is slower)\n    syncInBackground: true,\n\n    // you can pass extra params to the sync method\n    // see sync example below\n    syncParams: {\n      extraFetchOptions: {\n        // blahblah\n      },\n      someFlag: true\n    }\n  })\n  .then(ret =\u003e {\n    // found data go to then()\n    console.log(ret.userid);\n  })\n  .catch(err =\u003e {\n    // any exception including data not found\n    // goes to catch()\n    console.warn(err.message);\n    switch (err.name) {\n      case 'NotFoundError':\n        // TODO;\n        break;\n      case 'ExpiredError':\n        // TODO\n        break;\n    }\n  });\n\n// --------------------------------------------------\n\n// Save something with key and id.\n// \"key-id\" data size cannot surpass the size parameter you pass in the constructor.\n// By default the 1001st data will overwrite the 1st data item.\n// If you then load the 1st data, a catch(NotFoundError) or sync will be invoked.\nvar userA = {\n  name: 'A',\n  age: 20,\n  tags: ['geek', 'nerd', 'otaku']\n};\n\nstorage.save({\n  key: 'user', // Note: Do not use underscore(\"_\") in key!\n  id: '1001', // Note: Do not use underscore(\"_\") in id!\n  data: userA,\n  expires: 1000 * 60\n});\n\n// load\nstorage\n  .load({\n    key: 'user',\n    id: '1001'\n  })\n  .then(ret =\u003e {\n    // found data goes to then()\n    console.log(ret.userid);\n  })\n  .catch(err =\u003e {\n    // any exception including data not found\n    // goes to catch()\n    console.warn(err.message);\n    switch (err.name) {\n      case 'NotFoundError':\n        // TODO;\n        break;\n      case 'ExpiredError':\n        // TODO\n        break;\n    }\n  });\n\n// --------------------------------------------------\n\n// get all ids for \"key-id\" data under a key,\n// note: does not include \"key-only\" information (which has no ids)\nstorage.getIdsForKey('user').then(ids =\u003e {\n  console.log(ids);\n});\n\n// get all the \"key-id\" data under a key\n// !! important: this does not include \"key-only\" data\nstorage.getAllDataForKey('user').then(users =\u003e {\n  console.log(users);\n});\n\n// clear all \"key-id\" data under a key\n// !! important: \"key-only\" data is not cleared by this function\nstorage.clearMapForKey('user');\n\n// --------------------------------------------------\n\n// remove a single record\nstorage.remove({\n  key: 'lastPage'\n});\nstorage.remove({\n  key: 'user',\n  id: '1001'\n});\n\n// clear map and remove all \"key-id\" data\n// !! important: \"key-only\" data is not cleared, and is left intact\nstorage.clearMap();\n```\n\n### Sync remote data(refresh)\n\nThere are two ways to set the sync method.\nYou can pass the sync method in the constructor's parameter, as a function in an object,\nor you can define it at any time as shown below:\n\n```js\nstorage.sync = {\n  // The name of the sync method must be the same as the data's key name\n  // And the passed params will be an all-in-one object.\n  // You can return a value or a promise here\n  async user(params) {\n    let {\n      id,\n      syncParams: { extraFetchOptions, someFlag }\n    } = params;\n    const response = await fetch('user/?id=' + id, {\n      ...extraFetchOptions\n    });\n    const responseText = await response.text();\n    console.log(`user${id} sync resp: `, responseText);\n    const json = JSON.parse(responseText);\n    if (json \u0026\u0026 json.user) {\n      storage.save({\n        key: 'user',\n        id,\n        data: json.user\n      });\n      if (someFlag) {\n        // do something for some custom flag\n      }\n      // return required data when succeed\n      return json.user;\n    } else {\n      // throw error when failed\n      throw new Error(`error syncing user${id}`));\n    }\n  }\n};\n```\n\nIn the following example the sync method is called, when you invoke `storage.load`:\n\n```js\nstorage.load({\n\tkey: 'user',\n\tid: '1002'\n}).then(...)\n```\n\nIf there is no user 1002 currently in storage, then storage.sync.user will be invoked to fetch and return the remote data.\n\n### Load batch data\n\n```js\n// Load batch data with an array of `storage.load` parameters.\n// It will invoke each key's sync method,\n// and when all are complete will return all the data in an ordered array.\n// The sync methods behave according to the syncInBackground setting: (default true)\n// When set to true (the default), if timed out will return the current value\n// while when set to false, will wait till the sync method completes\n\nstorage.getBatchData([\n\t{ key: 'loginState' },\n\t{ key: 'checkPoint', syncInBackground: false },\n\t{ key: 'balance' },\n\t{ key: 'user', id: '1009' }\n])\n.then(results =\u003e {\n\tresults.forEach(result =\u003e {\n\t\tconsole.log(result);\n\t})\n})\n\n// Load batch data with one key and an array of ids.\nstorage.getBatchDataWithIds({\n\tkey: 'user',\n\tids: ['1001', '1002', '1003']\n})\n.then( ... )\n```\n\nThere is an important difference between the way these two methods perform:\n**getBatchData** will invoke separate sync methods for each different key one after the other when the corresponding data is missing or not in sync. However, **getBatchDataWithIds** will collect a list of the missing data, pushing their ids to an array, and then pass the array to the single corresponding sync method once, reducing the number of requests, so you need to implement array query on the server side and handle the parameters of sync method properly. Note that the id parameter can be a single string or an array of strings.\n\n#### You are welcome to ask any question in the [issues](https://github.com/sunnylqm/react-native-storage/issues) page.\n\n## Contributors\n\nThis project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].\n\u003ca href=\"https://github.com/sunnylqm/react-native-storage/graphs/contributors\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/contributors.svg?width=890\u0026button=false\" /\u003e\u003c/a\u003e\n\n\n## Backers\n\nThank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/react-native-storage#backer)]\n\n\u003ca href=\"https://opencollective.com/react-native-storage#backers\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/backers.svg?width=890\"\u003e\u003c/a\u003e\n\n\n## Sponsors\n\nSupport this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/react-native-storage#sponsor)]\n\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/0/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/0/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/1/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/1/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/2/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/2/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/3/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/3/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/4/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/4/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/5/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/5/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/6/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/6/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/7/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/7/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/8/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/8/avatar.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/react-native-storage/sponsor/9/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/react-native-storage/sponsor/9/avatar.svg\"\u003e\u003c/a\u003e\n\n\n","funding_links":["https://opencollective.com/react-native-storage"],"categories":["Components","awesome-web-storage [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome)","JavaScript","存储（Storage）"],"sub_categories":["Storage","Different Storage APIs","Storage / Database"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsunnylqm%2Freact-native-storage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsunnylqm%2Freact-native-storage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsunnylqm%2Freact-native-storage/lists"}