首页 > 解决方案 > React native asyncstorage get data

问题描述

I am using componentWillMount in react-native to get data from API. But when I tried to get the token stored while login. It cannot work. I have no idea whats the problem/

componentWillMount(){

        let token = this.getData
        fetch('http://192.168.0.125:8887/api/auth/activities/index',{
            method: 'POST',
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '. token,
            },
        })
        .then((response) => response.json())

        .then((res) => {
            //console.log(res)

        })
        .catch((e) => console.log('Error: ', e))
    }

    getData = async () => {
        let token =''
        try{
            token = AsyncStorage.getItem('id_token')
            console.log(token)
        }catch (error) {
            console.log('AsyncStorage error: ' + error.message);
        }
        return token
    }

标签: javascriptreact-nativeasyncstorage

解决方案


well, AsyncStorage.getItem() is a promise, so you need to use await to get the token before console.log.

const token = await AsyncStorage.getItem('id_token')


推荐阅读