Retrieving an item from AsyncStorage produces a Promise

Insight

I am attempting to utilize AsyncStorage to store a Token after a successful login. The token is obtained from the backend as a response once the user clicks on the Login button. Upon navigating to the ProfileScreen, I encounter difficulties in retrieving the saved token.

Challenge

Upon trying to retrieve the item in the ProfileScreen and logging it to the console, I discover that I am getting a Promise object filled with nested objects, within which I can locate my desired value. How can I extract this value effectively?

Solution

Utilities/AsyncStorage.js (Contains helper functions for storing and retrieving items)

const keys = {
jwtKey: 'jwtKey'
}

const storeItem = async (key, item) => {
  try {
    var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
    console.log('Item Stored !');
    return jsonOfItem;
  } catch (error) {
    console.log(error.message);
  }
};

const retrieveItem = async key => {
  try {
    const retrievedItem = await AsyncStorage.getItem(key);
    const item = JSON.parse(retrievedItem);
    console.log('Item Retrieved !');
    return item;
  } catch (error) {
    console.log(error.message);
  }
  return;
};

LoginScreen.js (After clicking on the login button, receiving a token response from backend)

const LoginScreen = ({componentId}) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const loginPressed = async () => {
    await axios
      .post('localhost', {
        email,
        password,
      })
      .then(function(res) {
        console.log(res);
        storeItem(keys.jwtKey, res.data.token);
        push(componentID, views.profileScreen());
      })
      .catch(function(error) {
        console.log(error);
      });
  };

ProfileScreen.js (Attempting to retrieve and use the token on this screen)

const ProfileScreen = ({componentID}) => {
let testingAsync = retrieveItem(keys.jwtKey);
console.log(testingAsync);

The log displays a promise object containing nested values.

Promise{_40:0, _65:0 , _55:null, _72:null}

The actual token value can be found within the _55 property of the object.

Answer №1

I appreciate the feedback! I was able to resolve the problem by incorporating .then() in my ProfileScreen as suggested by @Bergi in their comment. Subsequently, after receiving another input, I implemented an async/await function within a useEffect hook in my ProfileScreen to avoid repetition and successfully resolved the issue!

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

Tips for modifying an HTML element's attribute when a button is clicked, both in the client and server side

Context: This question delves into the fundamental concepts of AJAX. I have been studying this tutorial along with this example for the JavaScript part, and this resource (the last one on the page) for the PHP segment. Imagine a scenario where a JavaScri ...

Transition smoothly with a fade effect when switching between models

I am in the process of creating a basic query system. While I can display questions one at a time, I am looking to incorporate transitions when switching between questions. To further illustrate my issue, I have set up a Plunker demonstration: http://plnk ...

When developing a node.js project using VMWare's shared folder, how can you manage the node_modules folder?

My current project needs to run on Linux, but I am using a Windows computer. This means I have to use a VM. Despite wanting to use WebStorm, I am avoiding JB Gateway due to its numerous bugs. My solution was to utilize the VMWare share folder function. Ho ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

Enhance the efficiency of time tracking function

I have been using a nodejs module to track the execution time of different parts of my application. // polyfill for window.performance.now var performance = global.performance || {} var performanceNow = performance.now || performance.mozNow ...

The JavaScript function will only run after the user clicks the button twice

I attempted to create a button that toggles the visibility of a div element. Initially, I added the "onclick" event to the button and wrote this function: function showElement() { var element = document.querySelector('.blocks-fnd-div'); if ...

Tips for transforming a date into a time ago representation

Can someone help me with converting a date field into a "timeago" format using jquery.timeago.js? $("time.timeago").timeago(); var userSpan = document.createElement("span"); userSpan.setAttribute("class", "text-muted"); userSpan.appendChild(document.crea ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

React.js - Implementing a Delayed Loading Indicator to Prevent Flickering

How do I implement a loading indicator in React that only appears if the loading state is true for over 1 second, and if it resolves before 2 seconds, show the indicator for at least 1 second? In Angular JS, there was a similar question with 5 conditions: ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...

Upon invoking the useEffect function, the default value can be seamlessly established within the input field of the antd library

I have a function called loadProfile that I need to execute within the useEffect hook. When this function is triggered, I want the name Mario to be automatically displayed in the input field labeled name. How can I set this default value using the antd lib ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

Utilizing jQuery to Determine Character Count

I've tried everything on the site, but nothing seems to be working. I'm attempting to create a function that triggers when the character count in a div exceeds a certain number, but it's not functioning as expected. Any assistance would be g ...

NodeJS: Steps to efficiently transfer data from a master table to two separate tables while maintaining the order of the master table, utilizing asynchronous code wherever applicable

Are promises or async/await being used for this task? For instance: if the master table has columns (id, uuid, op_1, op_2) then the new tables should be table1(id, uuid) table2(id, op_1, op_2) The priority is to maintain the same order as the master ta ...

support for fullscreenchange event across different browsers

I have been exploring how to add an event listener for fullscreen change in my Next.js app, and I noticed that many example codes use the webkit, moz, and ms prefixes together. However, after testing on Edge, Chrome, and Firefox, it seems that using only t ...