Challenges with React Native's AsyncStorage

When I try to access data stored in asyncStorage using the 'getToken' and 'getMail' functions in the code snippet below, I encounter an issue where the data appears empty when I initially open the page on the emulator. However, upon saving the file by pressing 'ctrl+s', the data loads correctly. What could be causing this problem?

App.js Page

    getToken: async () => {
      const token =  AsyncStorage.getItem('userToken');
      return token;
    },
    getMail: async () => {
      const mail =  AsyncStorage.getItem('userMail');
      return mail;
    },

OrderListScreen Page

        getToken().then((res) => {
            if(res){
            setToken(res);
            console.log(token)
            }else {
              setToken('');
            }
        });
        getMail().then((res) => {
            if(res){
            setMail(res);
            console.log(mail)
            }else {
              setMail('');
            }
        });

Answer №1

Make sure to add the await keyword before calling AsyncStorage.getItem:

getToken: async () => {
  const token = await AsyncStorage.getItem('userToken');
  return token;
},
getMail: async () => {
  const mail =  await AsyncStorage.getItem('userMail');
  return mail;
},

Note that when setting state, you may not see the updated value immediately in the next line after calling the setter function.

getToken().then((res) => {
    if(res){
    setToken(res);
    console.log(token); //The updated value may not be available immediately here due to asynchronous state updates in React
    console.log("res : ", res);
    }else {
      setToken('');
    }
});
getMail().then((res) => {
    if(res){
    setMail(res);
    console.log(mail)//The updated value may not be available immediately here due to asynchronous state updates in React
    console.log("Email Res : ", res);
    }else {
      setMail('');
    }
});

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

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

What is the method to access a form using jQuery? How can I extract the percentage symbol "%" from the entered amount?

I am working on developing a fee calculator using jQuery. In order to achieve this, I need to access forms. Here is the code I have so far: <form id="fee"> <input type="text" title="fee" placeholder="Place the amount that you would like to se ...

Filters in VueJs do not produce any results

Example of Basic Code <!DOCTYPE html> <html> <head> <title>My First Vue Application</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cfcc ...

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

instructions on how to eliminate slideUp using jquery

I am trying to eliminate the slide-up function from my code $( document ).ready(function() { $("#tabBar ul.buttons > li > a").on("click", function(e){ //if submenu is hidden, does not have active class if(!$(this).hasClass("activ ...

Navigate to the following div, navigate back to the previous div

I am attempting to implement a div navigation system with next/previous buttons. Despite searching extensively on Google, I have not found the exact solution I am looking for. First and foremost, I want to maintain the integrity of my html structure. < ...

What is the method for defining unassociated variables in Angular?

I am currently seeking a solution to retrieve data from the server (or JSON file) and store it in two separate variables: 'firstVariable' for manipulation purposes, and 'secondVariable' for storing the original unaltered data. However, ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

Is sending cookies the sole method to convey a directive from a server to a client for the execution of JavaScript code?

Simply put: How can a server send a message to a client to run JavaScript code on a page? It's not an Ajax request, but a basic GET browser-server request. Imagine this code in my app's front-end JavaScript file: if( condition_1 ) { FB.get ...

Node.js throwing error due to incorrect format of bind parameters as an array

I have been working with Nodejs/express and trying to implement a paramerized query in my API. However, I encountered the following error message in my console: Bind parameters must be array if namedPlaceholders parameter is not enabled Below is a snippet ...

Looking for a specific value in a switch case code written in JavaScript

Below is the code snippet found in my alert box or any variable. I need to update the values in product to different values such as 'Tremfya', 'Remicade', dynamically. These values are required for a specific product like "linename" and ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Error: The function isInitial of chunk cannot be found

Currently, I am attempting to build my program using the following command: "build": "NODE_ENV='production' webpack -p", However, I encountered an error message: node_modules/extract-text-webpack-plugin/index.js:267 var shouldE ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Using Conditions in AngularJS: Choosing Between Callbacks and Promises in a Service

I am currently faced with a specific scenario where I am uncertain whether to implement a callback or a promise. As someone who is relatively new to promises and just beginning to grasp their concept, I want to avoid falling into any potential anti pattern ...

What is causing my sorting algorithm to produce inaccurate results?

After finding this sorting function as the best answer to my question, I tested it with example data and it worked perfectly. However, when I tried it with my actual data, it didn't work as expected and I'm not sure why. You can view my data her ...