Is there localstorage in nativescript?

Naren picture Naren · Sep 13, 2016 · Viewed 11.2k times · Source

How to share the data across the pages which resides in application.Can anyone tell about localstorage in nativescript?

Answer

Emil Oberg picture Emil Oberg · Sep 13, 2016

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