Guide on utilizing the built-in storage functionality in Ionic 5

Hey there, I need a bit of assistance. In my application, I've added a function that allows users to switch between light and dark themes when they press a button. Everything seems to be working fine, except for one thing - whenever the application is restarted, the theme defaults back to light. Any ideas on how I can use Ionic's native storage to save the theme preference?

import { Component } from '@angular/core';
import { NativeStorage } from '@ionic-native/native-storage/ngx'
import { EmailComposer } from '@ionic-native/email-composer/ngx';



@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
theme:string = "light";

  constructor(public nativeStorage:NativeStorage, private emailComposer: EmailComposer) {}

  switchTheme(){
    if(this.theme=='light'){
      document.body.classList.add("dark");
      this.theme="dark";
      console.log(this.theme)
    } else {
      document.body.classList.remove("dark");
      this.theme='light';
      console.log(this.theme)
    }
  }

  sendEmail() {
    let email = {
      to:'my-mail',
      subject: 'My Feedback',
      isHtml: true 
    };

    this.emailComposer.open(email);
  }

}

Thank you in advance!

Answer №1

For Your Situation.

1. Begin by establishing a Default Theme; for example, let's consider light as the default option.

2. Store the theme in storage every time you make a change:

let selectedTheme = 'light';
this.nativeStorage.setItem('storedTheme', {theme: selectedTheme})
  .then(
    () => console.log('Item Stored!'),
    error => console.error('Error storing item', error)
  );
  1. Retrieve the storedTheme value in the ngOnInit lifecycle event.

    ngOnInit {
       this.nativeStorage.getItem('storedTheme')
       .then(
         data => console.log(data),//set theme here
        error => console.error(error)
      );}
    

4. Modify the theme Switch Method to accept parameterized input setTheme Method:

  setTheme(theme){
    if(theme=='dark'){
      document.body.classList.add("dark");
      this.theme="dark";
      //save in storage
    } else {
      document.body.classList.remove("dark");
      this.theme='light';
      console.log(this.theme)
    }
  }

Invoke this same method in step two to set the theme when retrieving it from Storage: setTheme(theme)

5. In the HTML code, use the following:

(click)="theme=='light'? setTheme('dark'):setTheme('light')"

Answer №2

Utilize the NativeStorage that has been injected for your use.

Referencing the official documentation:

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Item stored successfully!'),
    error => console.error('Error storing item', error)
  );

this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data),
    error => console.error(error)
  );

For more information, please visit: https://ionicframework.com/docs/native/native-storage

I trust this guidance will be beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

What is the correct way to write an asynchronous Express middleware function in Typescript?

Can anyone help me figure out how to correctly define a return value for an express middleware that utilizes async/await? I've been experimenting with different approaches but haven't found success yet. Additionally, I'm attempting to exten ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Angular 2 introduces one-way binding, which allows for modifications to be applied to both objects

How does one-way binding modify both objects? <component2 [obj]="obj1"></component2> Is there a way to make changes to obj without affecting obj1? It seems that only duplicating obj solves this issue. Is there another method in angular2 to a ...

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

Get a list of objects from a JSON array of objects using HTTP requests in Angular 5 with Typescript

I am trying to extract an array of objects from another JSON array, which is received through an HTTP request in Angular 5. My goal is to display the values in the console. I have successfully made the HTTP request and subscribed to the service. When usin ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

An error was encountered in compiler.js at line 1021, stating that an unexpected value 'UserService' was imported by the module 'UserModule'. It is recommended to add a @NgModule annotation to resolve this issue

As a PHP programmer new to Angular, I am facing an issue while trying to retrieve user properties from a Laravel API. When attempting this, I encountered the following error: compiler.js:1021 Uncaught Error: Unexpected value 'UserService' importe ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

When using Vue 3 with Typescript, encountering the error message "No overload matches this call" can be frustrating even when the function name is clearly defined. It appears that the order of

While working with Vue 3 emit function and TypeScript, I encountered a strange error message. Here's an example code snippet to reproduce the issue: export default defineComponent({ emits: { emit1: (payload: number) => payload, emit2: (pa ...

Axios mandating the use of the "any" type for response type requirements

Currently, I am facing an issue while trying to retrieve data using Axios in my TypeScript React project. I have set the response type in axios to match CartItemType, however, Axios is enforcing the response type to be of CartItemType and any, which is cau ...

The interface IJobDetails cannot be assigned to type null

https://i.sstatic.net/cVVSs.png In the code snippet below, I have created an interface called ClientState1. Now, I am attempting to define a constant named descriptionJobDetails with the type ClientState1, specifically for IJobDetails. However, I am encou ...

In Next.js, I am experiencing an issue where the Tailwind class is being added, but the corresponding

I'm currently in the process of developing a board game where I need to track players and their positions on specific squares. My goal is to display a small colored dot on the square where each player is positioned. Here's a snippet of my templa ...

Creating personalized directives

Seeking help on Vue's custom directives with Typescript integration. Despite extensive search online and in chat rooms, I am unable to find any solutions. <button v-clickOutside="myFunc"> Click Outside </button> Implementing the ...

The data table fails to display updated information from the data source

After updating the data-array (FileDto), I am unable to see any changes reflected in the Datatable. I have tested outputting the data using ngFor, and it works perfectly fine. Here is the HTML code: <ngx-datatable class="material striped" [rows]= ...

Having difficulty in accessing the node modules

As a C#/C++ programmer new to nodejs, I am looking to incorporate typescript into my code. However, when attempting to import modules like fs or stream, I am encountering the following error: Module not found Interestingly, VisualStudio 2017 is able to ...

What is the most efficient method for restoring an object's color to its original state?

Currently, I am working on a typescript program that involves manipulating a collection of objects, all initially colored red (e.g. cup.material.color is red). My goal is to be able to change the color of one object, such as a cube, by pressing a certain ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

Using Typescript and React, we can pass a single data from the transferFilterValues.currency table to the search component in order to efficiently filter

I need to access the transferFilterValues and filter table by currencies with hardcoded options values. I am feeling lost and could really use a fresh perspective. It seems like query keys might play a role in this process, but I'm not familiar with ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...