Home > Mobile >  React Native AsyncStorage problem with non async function
React Native AsyncStorage problem with non async function

Time:10-06

I have the following function:

import uuid from "react-native-uuid";
import AsyncStorage from "@react-native-async-storage/async-storage";

export const UUID = GetUUID(); //uuid.v4(); //'62AA6918-ECF4-4436-A715-5018EA5CAADD';


export function GetUUID() {
  var id = uuid.v4();

  AsyncStorage.getItem('uuid', (err, result) => {
    if(result == null){
      AsyncStorage.setItem(
        "uuid",
        id
      );
    }else{
      id = result;
    }
    console.log(result);
  });

  return id;
}

Then in another file (react query) where we have all API calls I have the following function:

import {
  API
} from "./api";

import {
  UUID
} from "./constants";

export function testMethod(email: string) {

  const version = Constants.manifest.version

  const url = `${API}bookmark/${email}?&uuid=${UUID}&v=${version}&p=true`;
  
  // UUID IS NOT RETURNING A VALUE, IT SEEMS TO BE RETURNING A PROMISE

  return axios({
    method: "GET",
    url: url,
    headers: {
      "Content-Type": "multipart/form-data",
      Accept: "multipart/form-data",
    },
  }).then((res) => {

    return res.data;
  });
}

Seems the problem is related to Async or Await, when calling GetUUID() method we are not getting either a new UUID or the one already in the Storage. I have to deal with it all day and can't find a solution.

Any clue?

CodePudding user response:

getItem should return a Promise object. So make GetUUID async and await the getItem call (returning the appropriate id depending on whether it exists in storage as you've implemented).

export async function GetUUID() {
  try {
   let id = uuid.v4();

   const res = await AsyncStorage.getItem('uuid')
   if (res !== null) id = res;

   return id;
  } catch (e) {
    console.log(e);
  }

}

Unless you're in an env supporting top level await, With you're current code arrangement, you'll either need to await UUID (which is a promise) when you import, or export the GetUUID method and invoke it in testMethod, which would need to be made async.


import {
  API
} from "./api";

import {
  UUID, GetUUID
} from "./constants";

export async function testMethod(email: string) {
   // use either to get uuid and then use to interpolate url: 
   // 1. const uuid = await UUID; 
   // 2. const uuid = await GetUUID();

   ...
}
  • Related