Code Monkey home page Code Monkey logo

react-native-default-preference's Introduction

npm version

react-native-default-preference

Use SharedPreferences (Android) and UserDefaults (iOS) with React Native over a unified interface. All data is stored as a string. If you need to support more complex data structures, use serialization/deserialization (e.g. JSON).

Getting started

$ npm install react-native-default-preference --save

React Native >= 0.60

$ cd ios && pod install

React Native <= 0.59

$ react-native link react-native-default-preference

Manual installation

iOS

  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modulesreact-native-default-preference and add RNDefaultPreference.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libRNDefaultPreference.a to your project's Build PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)<

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import com.kevinresol.react_native_default_preference.RNDefaultPreferencePackage; to the imports at the top of the file
  • Add new RNDefaultPreferencePackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
    include ':react-native-default-preference'
    project(':react-native-default-preference').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-default-preference/android')
    
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
      compile project(':react-native-default-preference')
    

Usage

import DefaultPreference from 'react-native-default-preference';

DefaultPreference.get('my key').then(function(value) {console.log(value)});
DefaultPreference.set('my key', 'my value').then(function() {console.log('done')});

API

function get(key: string): Promise<string | undefined | null>;
function set(key: string, value: string): Promise<void>;
function clear(key: string): Promise<void>;
function getMultiple(keys: string[]): Promise<string[]>;
function setMultiple(data: {[key: string]: string}): Promise<void>;
function clearMultiple(keys: string[]): Promise<void>;
function getAll(): Promise<{[key: string]: string}>;
function clearAll(): Promise<void>;

/** Gets and sets the current preferences file name (android) or user default suite name (ios) **/
function getName(): Promise<string>;
function setName(name: string): Promise<void>;

Cordova Native Storage Compatibility

This module is compatible with cordova-plugin-native-storage.

Android

You need to use the same SharedPreference as in the cordova plugin, to do so add the following line:

import { Platform } from 'react-native';
// ...
if (Platform.OS === 'android') DefaultPreference.setName('NativeStorage');

iOS

You don't need to change the name, as cordova-plugin-native-storage uses the default value.

react-native-default-preference's People

Contributors

cgoldsby avatar cristovao-trevisan avatar dozel avatar emnsen avatar erkie avatar gabrieleprestifilippo avatar jesuskfc avatar juliano-abr avatar karanjthakkar avatar kevinresol avatar knarfytrebil avatar magrinj avatar marcelkalveram avatar msftenhanceprovenance avatar mspanc avatar nekith avatar tagir-a avatar trevorah avatar vennos5 avatar ybrsangwoo 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

react-native-default-preference's Issues

New npm release?

Hey there! 👋

Thanks fore this package! We've been using it successfully with Jitsi Meet for quite a while now! I noticed we have our version pinned to a commit because we need the Xcode 12 fixes. Those are not currently on any release. Any chance you could make one?

How to get and return value from a custom function

I've a custom function like this,

export function getValueFromDevice(key) {
  key = key.toString();
  DefaultPreference.get(key).then(function (value) {
    console.log(value); //I'm getting value here
    return value;
  });
};

Calling the function,

import * as GeneralHelper from './../helpers/GeneralHelper';
const levelFromDevice = GeneralHelper.getValueFromDevice("level");
console.log(levelFromDevice) //It's showing undefined

Please help.
Thanks in advance.

Update to 1.3.2 from 1.3.1 makes android release crash

If I update from 1.3.1 to v1.3.2 i get following error:

error: cannot find symbol
import com.reactlibrary.RNDefaultPreferencePackage;
                       ^
  symbol:   class RNDefaultPreferencePackage
  location: package com.reactlibrary

Wat's the change in new version?
RN version: 0.56

sharing credentials across schemes

is this library provide sharing a login state like a token or some user defaults across schemes

useCase I am considering:
App A : User logins with this app and assigned a jwt and close this app
APP B( with the same source but different scheme): user open this app and is automatically signed in

Support tvos

this package works with tvos but the podspec doesn't support it.

Could we add support for tvos on podspec?

tvOS support not released

Hello,

I noticed that for some reason the .podspec file in the release 1.4.1 doesn't contain tvOS as one of the targets.
That results in an annoying error while using the package.
The fix is already there in the repo, but for some reason, it's not included in the released archive.

Could you tell why?

get from native code

Hi, first, thanks for this lib.
Second, i need to get data from Siri Intent, that is not in react native project.

i have tried this:
React Native:
await DefaultPreference.setName('group.myapp.test')

Objective C

NSUserDefaults *defaults = [[NSUserDefaults alloc] init];
  [defaults addSuiteNamed:@"group.myapp.test"];
 NSArray<NSString *> *defaultAsDic = [[defaults dictionaryRepresentation] allKeys];

But my custom keys arent in defaultAsDic.

Can someone help me please?

Doesn't work with Android buildTools 28.0.3

The build has a warning first:

> Configure project :react-native-default-preference
WARNING: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.3.1.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

Finally, it fails with the following message:

* What went wrong:
Execution failed for task ':react-native-default-preference:verifyReleaseResources'.
java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
 /Users/me/Projects/scanner/node_modules/react-native-default-preference/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
 /Users/me/Projects/scanner/node_modules/react-native-default-preference/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
  /Users/me/Projects/scanner/node_modules/react-native-default-preference/android/build/intermediates/res/merged/release/values/values.xml:2714: error: resource android:attr/fontVariationSettings not found.
  /Users/me/Projects/scanner/node_modules/react-native-default-preference/android/build/intermediates/res/merged/release/values/values.xml:2715: error: resource android:attr/ttcIndex not found.
  error: failed linking references.

From a few stack overflow posts it seems upgrading to buildTools 28.0.x should fix this.

Access content on shared extension

I would like to access a storage variable on my share extension app. When I call the getAll() on my main app works, but the variable is not there when called on my share extension app. Both apps are on the same app group.

What am I doing wrong?

Why does the API return promises?

Hi, I'm just wondering what benefit this could have, as it complicates usage. Why wouldn't you just always want it to work synchronously?

method does not override or implement a method from a supertype @Override.

There is an error:
/node_modules/react-native-default-preference/android/src/main/java/com/reactlibrary/RNDefaultPreferencePackage.java:19: error: method does not override or implement a method from a supertype
@OverRide
^
1 error
:react-native-default-preference:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

I am using RN 0.51

hard coded buildToolsVersion causing warning after upgrading to RN 0.57

Configure project :react-native-default-preference
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The specified Android SDK Build Tools version (25.0.3) is ignored, as it is below the minimum supported version (27.0.3) for Android Gradle Plugin 3.1.4.
Android SDK Build Tools 27.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '25.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

TypeScript Typings

For those building in TypeScript for reasons, perhaps it would be helpful to include typings. I've whipped this up as a reference that I use in my projects.

declare module 'react-native-default-preference' {
    export default class DefaultPreference {
        static get(key: String): Promise<String>;
        static set(key: String, value: String): Promise<void>;
        static clear(key: String): Promise<void>;
        static getMultiple(keys: Array<String>): Promise<Array<String>>;
        static setMultiple(data: Object): Promise<void>;
        static clearMultiple(keys: Array<String>): Promise<void>;
        static getAll(): Promise<Object>;
        static clearAll(): Promise<void>;

        /** Gets and sets the current preferences file name (android) or user default suite name (ios) **/
        static getName(): Promise<String>;
        static setName(name: String): Promise<void>;
    }
}

getMultiple not working

I am trying to read four strings from preferences.

Its giving me this error in android.
device-2018-05-18-102213

react-native version: 0.54
react-native-default-preferences version: 1.3.1

This is the code I have written to get multiple data:
```
DefaultPreference.get(['MAJOR', 'MINOR', 'LATITUDE', 'LONGITUDE']).then((data) => {
console.log('data = ', data);
});


RCTBridgeModule.h not found

Hello!

When I try to build my project in XCode, I get an 'RCTBridgeModule.h not found' error message in RCTBridgeModule.h. I know it has something to do with the fact React.xcodeproj was removed in a previous react-native update, but I was wondering if there was a fix for that problem.

Thank you!

Does not provide access to default preferences on Android

react-native-default-preferences is creating its own preferences scope on Android called "react-native" instead of reading/writing deafult preferences as the name implies. This prevents reading and writing global preferences that other libraries interact with, such as an IAB privacy string for purposes such as CCPA and GDPR compliance.

Sharing defaults between RN app and Swift share extension

I presume this is more like user error than an issue with the library but I posted on Stack Overflow and haven't had any luck.

I have a RN app where I am setting the user token as a Default, however when I try to access it in Swift share extension (same app group), it returns nil. More detail is on the Stack Overflow link below. Perhaps I'm not using it correctly?

https://stackoverflow.com/questions/48574639/share-userdefaults-between-react-native-app-and-swift-share-extension

Would really appreciate any suggestions!

Add a change listener mechanism based on Keys

Currently I use the Settings API from react native. This supports a Methode watchKeys to listen to changes via NSUserDefaultsDidChangeNotification. Additionally I needed a wrapper to support change notifications via its set() method, as NSUserDefaultsDidChangeNotificationonly gets triggered as the NSUserDefaults gets changed from outside the app. Both is needed for a react native app to listen correctly to NSUserDefaults changes. Any chance you could implement this?

Access data while phone is locked

I use this package for our call app and it works very well! Thanks for great library! I prefer it over AsyncStorage as it is simple and do not use SQLLite DB and also the ability to pass data between native and js code.
But I have a specific case: When phone is locked and user receives a voip push token and show CalKit accept/decline modal window, if user just slide to answer the call, then app starts and all js code runs, but when it tries to read values from NSUserDefaults using DefaultPreference those values is null, because the phone is still locked and code does not have access to NSUserDefaults (access is blocked).

Is there any way to store not so secure data in some place available to read even if the phone is locked? And specify a parameter available during lock or available only after unlock?

Access UserDefaults values from Swift

I was hoping to access a value which was set by the react native side from the swift. But it was not successful.
RN:
DefaultPreference.set('token', 'myToken').then(function() {console.log('done')});
Swift:
UserDefaults.standard.string(forKey: "token") ?? ""

Is that not possible with this package?

LICENSE Information missing for this package

Hi,

Can you please add the license information for the package, in my company quality team not allowing to use this package with out the license information.

Best Regards
Narayana.

Print quotes cause builds to fail

The file ios/RNDefaultPreference.h contains print quotes instead of regular ones causing builds to fail:

zrzut ekranu 2018-11-22 o 14 01 04

E.g. the code is

#elif __has_include(“RCTBridgeModule.h”)

but it should be

#elif __has_include("RCTBridgeModule.h")

New maintainer

Hi Kevin, this library is something I'm currently using in a client project, and was considering writing an extensions like this myself.

I'd be happy to become a maintainer. Let me know if you're still looking for someone. Thanks!

Undefined is not an object

I got this error when try to use the module, occurred on both android and ios

undefined is not an object (evaluating '_reactNativeDefaultPreference2.default.get')

Do you have any idea why ?

Thanks so much.

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.