Preserve boolean data using AsyncStorage within redux for efficient data storage

When I click a button, I want to toggle the state between "true" and "false" and save it using AsyncStorage in a React Native app with Redux. Can someone review my code and help me correct it if needed?

import { AsyncStorage } from "react-native";
import {
  START_TOOLTIP_BUDGET,
  STOP_TOOLTIP_BUDGET
} from "../actions/ActionTypes";

const INIT_STATE = true;
export default (state = INIT_STATE, action) => {
  switch (action.type) {
    case START_TOOLTIP_BUDGET:
      AsyncStorage.setItem("INIT_STATE", JSON.stringify(true));
      return INIT_STATE;

    case STOP_TOOLTIP_BUDGET:
      AsyncStorage.setItem("INIT_STATE", JSON.stringify(false));
      return INIT_STATE;
    default:
      return state;
  }
};

Answer №1

Achieving correct results is possible, but ensure that when you return INIT_STATE, it returns true or false in order to access the current data for your class. Otherwise, you will always receive a true response.

export default (state = INIT_STATE, action) => {
  switch (action.type) {
    case START_TOOLTIP_BUDGET:
      AsyncStorage.setItem("INIT_STATE", JSON.stringify(true));
      return true;

    case STOP_TOOLTIP_BUDGET:
      AsyncStorage.setItem("INIT_STATE", JSON.stringify(false));
      return false;
    default:
      return state;
  }
};

You can then retrieve this information from the class that initiated the action, and also access the AsyncStorage item:

AsyncStorage.getItem("INIT_STATE")
    .then(req => JSON.parse(req))
    .then(data => {
        if (data !== null) { 
          console.log(data); // true or false 
        }
    }).done();

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

Struggling to imitate RestTemplate using MockRestServiceServer, however, the body consistently appears to be null

Currently, I am attempting to simulate the behavior of RestTemplate using MockRestServiceServer. Interestingly, while debugging my test, I have discovered that the response entity consistently displays the correct status and content-type (I even tried out ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

Error Encountered During iOS Air Native Extension Compilation

Attempting to create a native extension in AIR for the nativeCamera Extension in an iOS app. This extension should open the camera on iOS when a button is clicked on Flex. The ANE has been created and included in the Flex code, but upon building for iPA, t ...

Using Swift: A guide to establishing IBOutlets from a different controller

I am encountering an issue with hiding my IBOutlet. Even though setting the text to an empty string works fine, directly accessing the IBOutlet results in an error stating "unexpectedly found nil while unwrapping optional value". Attempting to set the IBO ...

Halt the camera preview in the barcode scanning application

Currently, I am in the process of building a barcode scanning application using the open source ZXing library. You can find the link to the project here: https://github.com/ShyykoSerhiy/ZXingQuickStart/tree/master/src/com/shyyko/zxing/quick Given that I a ...

Mismatched MongoOperations 'id' selection resulting in a null value

While working with the Spring-Data-MongoDB 1.1.1.RELEASE, I encountered an issue where any query using "id" as a selector would return null: Query.query(Criteria.where("id").is("5X"))) Interestingly, when I utilized the Mongo class within the Java driver ...

IONIC 3 [ERROR] There was a problem encountered during the execution of cordova run android, resulting in an exit code of 1

While trying to run the command 'ionic cordova run android' for Ionic 3, I encountered an error that has left me stumped. Here's a snapshot of the error message: This Result Error [13:29:45] preprocess started ... [13:29:45] deeplinks sta ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Jest is throwing an error message stating that it cannot read properties of undefined, specifically trying to read the value of '

Recently, I started exploring Jest and created a test to verify multiple calls to a database from a specific URL. When running the test using the command below: npx jest --watchAll file.test.js Initially, everything seems to work fine. However, if I make ...

Ways to eliminate project title from the URL

After removing the hash tag from the URL with $locationProvider.html5Mode(true), I attempted to address the refresh issue by adding the following code to my .htaccess file: Options +FollowSymlinks RewriteEngine On RewriteBase /test/ RewriteCond %{REQUEST_ ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

The property express.json() is not recognized

Why doesn't Typescript recognize the express.json() function, even though many tutorials claim it should compile without errors? Could I have overlooked something in my code? An example tutorial that suggests this code works: https://auth0.com/blog/n ...

Can media queries be used to disable script tags in order to prevent them from downloading?

In order to create a website that is responsive, I choose to disable certain content in the mobile versions (or add content in the desktop/tablet version). By disabling this content, I can eliminate the need for including specific javascript files. This wi ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

Is there a way to fix the close button on the menu so that it works more than once?

I have developed a JavaScript-powered navbar, but I am facing an issue with the closing button. It seems to work only once. If I try to open and close the menu repeatedly, the closing button stops working. I suspect there might be an error in my code, but ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Log4j generates a "target" directory containing a blank file named "camel-spring-redis-test.log" within it

My log file seems to be working fine, but it's also creating a folder named "target" and an empty file called "camel-spring-redis-test.log". Below is the content of my log.properties: log4j.rootLogger=INFO, file log4j.appender.file=org.apache ...

table headers with interactive buttons for switching between various table views

Can someone provide guidance on how to implement 2 custom buttons in the header of a UITableView? When one of these buttons is clicked, a new table view should be loaded. Your assistance is greatly appreciated! ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...