Search code examples
javascriptreact-nativefetchasyncstorage

Using async correctly while accessing AsyncStorage


I'm working on a React Native app which uses jwt tokens to access my backend API. I'm trying to save the token in AsyncStorage but looks like I'm not using async correctly.

I have a utility that helps me set my fetch options and this is where I'm trying to also grab the jwt token from AsyncStorage but I haven't been able to use async correctly to get the token. Either I'm ending up with what looks like an unresolved promise or getting an error that tells me that I'm using await incorrectly.

I could use some help in reading my jwt token correctly in my fetch utility.

Here's what my utility looks like:

import { getAccessToken } from '../utils/my-utils';

export const fetchOptionsGet = async () => {

    getAccessToken().then(token => {

        return {
            method: 'GET',
            mode: 'cors',
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
            }
        };
    });
}

And this is the code for getAccessToken() function:

import { AsyncStorage } from "react-native";

export const getAccessToken = async () => {

    const accessToken = await AsyncStorage.getItem("access_token");

    return accessToken;
};

I think the issue is that because I'm calling an async function from my fetchOptionsGet() function, it becomes an async function as well. In my API method, when I tried to call it with an await keyword, I get a compile error. If I wrap my fetch call to my API inside a .then(token => { // API call here }), then I get a react-redux error telling me that my function should return a simple object.

What's the right way to read my jwt token and use it in my fetch call?


Solution

  • export const fetchOptionsGet = async () => {
    
        const token = await getAccessToken();
        return {
            method: 'GET',
            mode: 'cors',
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
        }
    }
    

    await waits for the promise to resolve. Then you can return whatever you need to return.