简体   繁体   English

如何从异步存储中检索数据并在我的组件中使用它?

[英]How do i retrieve data from Async storage and use it in my component?

I have saved a user_id and token in Async storage and i can retrieve it in via console log.我在异步存储中保存了一个 user_id 和令牌,我可以通过控制台日志检索它。 with the retrive function.与检索功能。 So i know the set function is working perfectly, the functions in deviceStorage all Async.所以我知道 set 函数运行良好,deviceStorage 中的函数都是异步的。

The problem comes when trying to use the retrieved user_id & token in my component it returns undefined.尝试在我的组件中使用检索到的 user_id 和令牌时出现问题,它返回未定义。

How can i get an item from storage and use it later in my code, i want to use the token and userid for a fetch request.如何从存储中获取项目并稍后在我的代码中使用它,我想将令牌和用户 ID 用于获取请求。 Please help me and highlight the best way to do.请帮助我并强调最好的方法。

    import deviceStorage from "../components/services/deviceStorage";
    class Jobs extends Component {
    constructor() {
       super();
       this.state = {
       jobsData: [],
       isLoading: true
       };
      }

    componentDidMount() {


        deviceStorage.retrieveToken().then(token => {
            this.setState({
               token: token
                 });
        });

        deviceStorage.retrieveUserId().then(user_id => {
            this.setState({
               user_id: user_id
             });
        });


const opts = {
  method: "GET",

  headers: {
    "Content-Type": "application/json",
    Authorization: "Token " + this.state.token
  }
};

fetch("http://example.com/job/" + this.user_id, opts)
  .then(res => res.json())
  .then(jobs => {
    this.setState({
      jobsData: jobs,
      isLoading: false
    });
    console.log(jobsData);
  })
  .catch(error => {
    console.error(error);
  });
  }

  render {} 

Code for the retrieve and set检索和设置代码

import {AsyncStorage} from 'react-native';


const deviceStorage = {
    async storeItem(key, item) {
        try {
            //we want to wait for the Promise returned by AsyncStorage.setItem()
            //to be resolved to the actual value before returning the value
            var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
            return jsonOfItem;
        } catch (error) {
           console.log(error.message);
        }
    },
    async retrieveItem(key) {
        try {
            const retrievedItem = await AsyncStorage.getItem(key);
            const item = JSON.parse(retrievedItem);
           // console.log(item);
            return item;
        } catch (error) {
            console.log(error.message);
        }
        return
    }
};

export default deviceStorage;`

There are two ways to get the data stored in async storage:有两种方法可以获取存储在异步存储中的数据:

(1) Promise method. (1) 承诺法。 Here your code does not wait for the block to finish and returns promise which is accompanied by .then clause if the promise resolves and .catch clause if there is error.在这里您的代码不等待块完成并返回其承诺伴随着。然后条款,如果承诺解析和.catch条款中是否存在错误。

(2) Async and Await method. (2) Async 和 Await 方法。 This is more preferred, here your code waits for the execution before proceeding one of the example to refer is below:这是更可取的,在这里您的代码在继续执行以下示例之一之前等待执行:

retrieveData() {
 AsyncStorage.getItem("id").then(value => {
        if(value == null){
             //If value is not set or your async storage is empty
        }
        else{
             //Process your data 
        }
      })
        .catch(err => {
            // Add some error handling
  });

Second Method example:第二种方法示例:

async retrieveData() {
try {
 let value = await AsyncStorage.getItem("id");
 if (value !== null) {
  //you have your data in value variable
  return value;
 }
}
catch (error) {
// Error retrieving data
}


}

your retrieve data storage methods should look like this您的检索数据存储方法应如下所示

retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('TASKS');
    if (value !== null) {
      // We have data!!
      return value;
    }
  } catch (error) {
    // Error retrieving data
  }
  return null;
};

Adding to the previous solutions添加到以前的解决方案

//function to retrieve data
async function retrieveItem(key) {
 try {
  const retrievedItem =  await AsyncStorage.getItem(key); //dataType String
   const item = JSON.parse(retrievedItem);//dataType object
   return item;
 }  catch (error) {
   console.log(error.message);
 }
 return
}

//function call
retrieveItem(key).then((value) => {
          //unlike normal function call, this waits for the promise to complete
          return value;// actual value not the promise
          })
          .catch((error) => {
             console.log('Error: ' + error);
          }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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