简体   繁体   中英

React-Native retrieve API_URL from AsyncStorage and make in accessible in all app (for test purpose)

I am trying to retrieve the API_URL from AsyncStorage and make it accessible in all app, the storing and retrieving (in settings screen) is working fine but when I try to load the data in the App.js using useEffect hook, it returns null. Reloading the app is not working but as soon as I save the App.js (using CTRL-S) it works fine. Please let me know the correct way to do this.

import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";

export default function App() {


  const [hostState, setHostState] = useState(null);

  const getAHostInfoAsync = async () => {
    const hostInfo = AsyncStorage.getItem('host').then(
      setHostState(hostInfo)
    ).then(
      console.log(hostState)
    );


  };

  useEffect(() => {
    getAHostInfoAsync();
  }, []);

  module.exports = {
    host: hostState
  };


}

and using in another file:

import App from "../../../App";
const API_URL = App.host;

I think your issue is in the way you use async/then. instead of async await. I am not 100% sure that this is your issue. But if I change my async/await function to use async/then the way you are having it, my IDE says that the variable (hostInfo) might not have been initialised. In any case, I think this is a better syntax than with then.

const getAHostInfoAsync = async () => {
    const hostInfo = await AsyncStorage.getItem('host')
    setHostState(hostInfo)
    console.log(hostState)
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM