Retrieving the input data from AsyncStorage in React Native after user interaction

I'm encountering an issue with AsyncStorage while attempting to store user input data in JSON format. Despite my efforts to confirm the correct storage of the data using console.log, it consistently shows undefined. I am now wondering how I can access and print out the stored data to verify its accuracy. Any insights on this would be appreciated! Thanks!

Below is the desired JSON format for storing user inputs:

  ////JSON FORMAT////
  const MyRecipeData = [
    {
      name: recipeName,
      video_cover: selectedVideoCover,
      video_url: UploadVideo,
      servings: servingSize,
      channel_name: channelName,
      publish_date: uploadDate,
      ingredients: ingredientsInput,
      directions: directionsInput,
    },
  ];
  ////JSON FORMAT////

After clicking the upload button, the following functions are invoked, with an attempt to read the saved data through the getAllinput function. However, I am unsure if I am proceeding correctly:

  ////------- Save all DATA --------------------////
  const SaveAllInput = async () => {
    await AsyncStorage.setItem("MyRecipeData", JSON.stringify(MyRecipeData))
      .then(() => {
        alert("your Recipe " + MyRecipeData.name + " has been saved");
      })
      .catch(() => {
        console.log("error");
      });
    getAllInput();
  };
  ////------- Save all DATA --------------------////

  ////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
  const getAllInput = async () => {
    try {
      const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
      NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
      console.log(NewRecipeData);
      return NewRecipeData;
    } catch {
      console.log(error);
    }
  };
  ////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////

When checking the terminal, the console.log(NewRecipeData) displays [{}], indicating a problem with reading the data accurately. Despite trying to use getItem, I still receive either undefined or [{}].

Answer №1

const UpdatedRecipeData = await AsyncStorage.getItem("UpdatedRecipeData");
UpdatedRecipeData !== null ? JSON.parse(UpdatedRecipeData) : null;

Instead of using const and redefining the variable, try console.log like this:

const UpdatedRecipeData = await AsyncStorage.getItem("UpdatedRecipeData");
console.log(UpdatedRecipeData);

You are calling getAllInput(); without using await

  const SaveAllInputs = async () => {
    const MyUpdatedRecipeData = [
      {
        name: updatedRecipeName,
        video_cover: selectedVideoThumbnail,
        video_url: UploadedVideoUrl,
        servings: servingPortion,
        channel_name: creatorChannelName,
        publish_date: uploadPublishDate,
        ingredients: listIngredients,
        directions: stepDirections,
      },
    ];
    await AsyncStorage.setItem('MyUpdatedRecipeData', JSON.stringify(MyUpdatedRecipeData))
      .then(() => {
        alert('Your recipe ' + MyUpdatedRecipeData.name + ' has been saved');
      })
      .catch(() => {
        console.log('Error saving recipe data');
      });
    await getAllInput();
  };

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

What is the best way to retrieve the http.server object from the express application?

Currently, I am in the process of developing a server-side node.js application utilizing express to manage HTTP requests. In addition to this, I am incorporating websockets (socket.io) support into the application. The challenge I face is that I do not hav ...

An error occurred stating: "The require function is not defined in AngularJS and nodeJS."

I have searched through various similar questions here on SO, but none seem to provide a solution that fits my specific case. I am relatively new to using angularjs and nodejs, and I am encountering an issue that has me stuck. My goal is to save the input ...

Having trouble with the unresponsive sticky top-bar feature in Zurb Foundation 5?

According to the information provided on this website, it is recommended to enclose the top-bar navigation within a div element that has both the class "contain-to-grid" and "sticky". However, I have noticed that while the "contain-to-grid" class exists in ...

The page will reset to the main page after any action is taken

Recently, I encountered an issue with my asp .net website featuring a "masterpage." After making some modifications to the "masterpage," specifically involving an "onmouseover menu" with "javascript" and "ajax," one of my pages started redirecting back to ...

Iconic Side Navigation with collapsed button malfunctioning due to negative positioning

I'm facing two issues with my webpage. First: I have three buttons on the right side of my page that are supposed to behave like the buttons on this example. However, when you scroll, you can see that their position is incorrectly displayed "outside" ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

"What is the best way to manipulate arrays in vue.js using the map function

I'm currently dealing with a Vue code that incorporates anime.js. My code has grown substantially to over 1500 lines. In order for Stack Overflow to accept my question, I have only included 5 items of my sampleText, even though it actually consists of ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Zoom feature available on various images

My current setup includes one main image and multiple thumbnails that can be clicked to change the main image. The issue I encountered was when using jqzoom on the main image, the zoomed image would go blank after changing. After researching on stack overf ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Retrieve the index of a v-for loop and then send it as a parameter to a specific function

When working with a select element generated by a v-for loop in Vue, it is important to be able to retrieve the index of the selected option. This way, you can use that index in a function for further processing. However, I have been struggling to achieve ...

What is the best way to animate specific table data within a table row using ng-animate?

Are you working with Angular's ng-repeat to display a table with multiple rows? Do you wish to add an animation effect to specific cells when a user hovers over a row in the table? In the scenario outlined below, the goal is to have only certain cell ...

I'm struggling with a namespace conflict in Javascript - how can I access this value in the function call?

Having a bit of trouble figuring out how to obtain the desired value within this function. Any ideas? Thanks! temp = exotics[i].split(','); if ($.inArray(temp[0], tblProbables) != -1) { item = $("<li><a id='" + temp[0] + "&apo ...

Display a Button exclusively at the bottom row of a Table using just Javascript

I am currently working on a 4-column table with a "+" button in the last column. This button's purpose is to add an additional column when clicked. However, the button is appearing in all rows of the table, and I would like it to be displayed only in ...

Last month's display is currently unidentified

function calculateTime() { var Make_It_12_Hour = true; var currentTime = new Date(); var hour1 = currentTime.getHours() - 1; var hour2 = currentTime.getHours(); var hour3 = currentTime.getHours() + 1; var minutes = currentTime.getM ...