0
    const ACCESS_TOKEN = 'auth_token';

    var api = {

    async removeToken(){
        try {
            await AsyncStorage.removeItem(ACCESS_TOKEN);
            this.getToken(ACCESS_TOKEN);
        } catch (error) {
            console.log("something went wrong remove token")
        }
    },

    async storeToken(accessToken){
        try {
            await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
            this.getToken(ACCESS_TOKEN);
        } catch (error) {
            console.log("something went wrong store token")
        }
    },

    async getToken(){
        try {
            let token = await AsyncStorage.getItem(ACCESS_TOKEN);
            var parsedToken = JSON.parse(token).auth_token;
            console.log("getToken: " + parsedToken);
            return parsedToken;
        } catch (error) {
            console.log("something went wrong gettoken")
            return null;
        }
    },

    getTasks(){
        var url = "http://doit.unicrow.com/api/v1/tasks/";
        return fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': "Token" + this.getToken()
            }
        }).then(response => response.json())
    }
}

module.exports = api;

Hi everyone, i am doing a project with react js and i am having a problem with it. In the above code snippet in getTasks method, I want to call the token value that returns from getToken method . I couldn't do it with using "this". How can I do it? Thanks in advance.

1 Answer 1

1

you can do it by using state

maintain a local state as

{ token:"" } set the token in state as

async getToken(){
        try {
            let token = await AsyncStorage.getItem(ACCESS_TOKEN);
            var parsedToken = JSON.parse(token).auth_token;
            console.log("getToken: " + parsedToken);
           // return parsedToken;
this.setState({
token:parsedToken
})
        } catch (error) {
            console.log("something went wrong gettoken")
            return null;
        }
    },

and in your getTasks method access it from state as

   getTasks(){
        var url = "http://doit.unicrow.com/api/v1/tasks/";
        return fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': "Token" + this.state.token
            }
        }).then(response => response.json())
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help you:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.