Is there localstorage in nativescript?
Asked Answered
P

5

11

How to keep data in a NativeScript application persistent. Can anyone tell about localStorage in NativeScript?

Edit: Was looking for localStorage at the time.

Paola answered 13/9, 2016 at 6:4 Comment(2)
what do you mean by data accross the pages? Do you mean global variables or something?Autography
yes, i want access the data across the app.Paola
H
9

You can use either with global.foo, it will available for whole app or you can use application-settings module

var applicationSettings = require("application-settings");
//set somewhere like this
applicationSettings.set<Number|String|Boolean>("sharedVar",1);

//get sharedVar somewhere
applicationSettings.get<Number|String|Boolean>("sharedVar");//if empty it will be null

//or if u want default value if sharedVar wasn't defined
//and if sharedVar was defined then u will get content of sharedVar
applicationSettings.get<Number|String|Boolean>("sharedVar","Default Value");

DOCS:

https://docs.nativescript.org/cookbook/application-settings

https://docs.nativescript.org/api-reference/modules/_application_settings_.html

EDIT: had typo not globals but global :D

EDIT2: change names of function from applicationSettings and link for docs

Heist answered 13/9, 2016 at 6:40 Comment(2)
How large can these strings be?Plascencia
Probably limits is RAM size of target deviceHeist
T
26

Your question can be read in a variety of ways, making it a bit hard to give you a good answer but I'll try:

If you want to pass data from one page to another on navigation

Create a Navigation Entry with a context

var navigationEntry = {
    moduleName: "details-page",
    context: {info: "something you want to pass to your page"},
    animated: false
};
topmost.navigate(navigationEntry);

... and on the page you're navigating to, pick up that context:

function onLoaded(args) {
    console.log(args.object.navigationContext);
}

See documentation about Navigation

If you want to create data available throughout the app

Just create a singleton and request that, just as you would in any other Javascript app.

E.g.

file: myData.js

var data = {
    something: 'a value here',
    somethingElse: 1
    somethingMany: ['a', 'b', 'c']
};

exports.data = data;

In any file where you want to read that data:

var data = require("./myData.js").data;
console.log(data);

Read more about modules in Javascript

If you want to persist data on the local device

If you want to write and read data, so that you can save it between sessions:

For non-complex data, use application-settings. E.g.

var appSettings = require("application-settings");

appSettings.setString("stringKey", "String value");  // Writing
var value = appSettings.getString("stringKey", "No string value"); // Reading
// will return "No string value" if there is no value for "stringKey"

console.log(value)

Read the docs about application-settings

You can also write a file to the device, with the file-system module, e.g.

var documents = fs.knownFolders.documents();
var path = fs.path.join(documents.path, "FileFromPath.txt");
var file = fs.File.fromPath(path);

// Writing text to the file.
file.writeText("Something")
    .then(function () {
        // Succeeded writing to the file.
    }, function (error) {
        // Failed to write to the file.
    });

Read the docs about file-system

For databases there are modules you can use, such as the nativescript-sqlite and nativescript-couchbase

Tran answered 13/9, 2016 at 8:32 Comment(5)
"If you want to persist data on the local device" Is it a good practice to store sensitive data with this approach?Suzannsuzanna
@JDrake this data can be read by other applications and should NOT be used to store sensitive dataHypnotherapy
@Hypnotherapy could you elaborate? how can the data be read by other applications? on which platforms?Suzannsuzanna
@JDrake this uses unencrypted shared preferences on android. Any app with root level access can access this data. I haven't done much research about iOS. A lot of your users might use rooted phones and saving sensitive data like this is definitely a no brainer. Check out nativescript-securestorage though. That can be used to store sensitive data.Hypnotherapy
But what app has root access? Isn't it already bad that an app has root access? Wouldn't this allow the said app to do worse things? (I would really like to know, no sarcasm involved)Breastplate
H
9

You can use either with global.foo, it will available for whole app or you can use application-settings module

var applicationSettings = require("application-settings");
//set somewhere like this
applicationSettings.set<Number|String|Boolean>("sharedVar",1);

//get sharedVar somewhere
applicationSettings.get<Number|String|Boolean>("sharedVar");//if empty it will be null

//or if u want default value if sharedVar wasn't defined
//and if sharedVar was defined then u will get content of sharedVar
applicationSettings.get<Number|String|Boolean>("sharedVar","Default Value");

DOCS:

https://docs.nativescript.org/cookbook/application-settings

https://docs.nativescript.org/api-reference/modules/_application_settings_.html

EDIT: had typo not globals but global :D

EDIT2: change names of function from applicationSettings and link for docs

Heist answered 13/9, 2016 at 6:40 Comment(2)
How large can these strings be?Plascencia
Probably limits is RAM size of target deviceHeist
L
6

If you install the "nativescript-localstorage" plugin,

tns plugin install nativescript-localstorage

You will then have access to both SessionStorage and LocalStorage just as if you were using a browser.


From the docs:

To set a value:

require( "nativescript-localstorage" );
localStorage.setItem('Another Plugin', 'By Master Technology');
localStorage.getItem('Another Plugin'); // Returns: "By Master Technology"

or

const LS = require( "nativescript-localstorage" );
LS.setItem('Another Plugin', 'By Master Technology');
LS.getItem('Another Plugin');  // Returns: "By Master Technology"

Disclaimer I'm the author of said plugin.

Lichee answered 20/12, 2016 at 11:25 Comment(5)
how we can store the object ?Yasminyasmine
deprecated in nativescript 6 version...moved to a paid repoGunthar
Small clarification: The community version is still available as-is. New enhancements and bug fixes are in the ProPlugins.orgLichee
Does this plugin work in Nativescript 7 iOS ? I am getting error in iOSProlocutor
The community version should still be working, I don't know of anything that should have broken in it, but I no longer maintain it. The ProPlugins version I still maintain and it for sure works, as I use it in several apps.Lichee
A
1

A NativeScript plugin to add LocalStorage and SessionStorage If you are trying to use any libraries that use the localStorage/sessionStorage API; or you want a fairly simple storage engine; here it is.

check nativescript-localstorage module

Usage

To use the module you just require() it:

require( "nativescript-localstorage" );

or you can also import localstorage module on your app.module or your file.

import 'nativescript-localstorage';

and then use localStorage variable on your code like below.

localStorage.setItem('Another Plugin', 'By Master Technology');

This will enable the localStorage api. So then you can use it just like a browser.

You can also optionally do:

let LS = require( "nativescript-localstorage" );
LS.getItem('Another Plugin'); // Returns: "By Master Technology"
Alleenallegation answered 18/8, 2017 at 9:20 Comment(0)
A
1

If you are using NS8, use "application-settings" from @nativescript/core

For example:

import * as appSettings from "@nativescript/core/application-settings";
...
appSettings.setString("token", response.token);
appSettings.setString("userId", response.user.id.toString());
appSettings.setString("email", email);
Albata answered 1/7, 2021 at 2:8 Comment(1)
How large can these strings be?Plascencia

© 2022 - 2024 — McMap. All rights reserved.