Search code examples
javascriptreact-nativeasynchronousasyncstorage

How to get a value from local storage with asyncStorage and return it


I want to create a method that returns an auth header from a token stored in the local storage so it can be called from many ajax, like this:

const fetchUserInfo = (username) => {
  const requestString = apiBaseURL + 'access/user_info/'
  const form = {username: username}

  return axios.post(requestString, form, getAuthHeader())
    .then((Response) => {
      return {
        userInfo: Response.data,
        message: null
      }
    })
    .catch((Error) => {
      return getErrorMessage();
    });
}

In this case, getAuthHeader() is a method that must return a proper authorization header from a token stored in the local storage, so it must use asyncStorage in order to retrieve such token.

This is the code for getAuthHeader:

export const getAuthHeader = async () => {
  return await AsyncStorage.getItem('token')
    .then ((token) => {
      return {
        headers: {'Authorization' : 'Token ' + token}
      }
    })
    .catch ((error) => null)
}

The problem is that getAuthHeader() is not returning a header but some other object. I believe I am messing up with the asynchronous nature of asyncStorage, but I can't figure out how to get the value I need.


Solution

  • Yes, you are using async/await and .then (native) together. async/await already handles the .then syntax for you without you having to do it. So you do not need both together it's 1 or the other. Both examples below.

    Async/Await:

    export const getAuthHeader = async () => {
      try {
        const token = await AsyncStorage.getItem('token')
        if (!token) { return null }
        return {
            headers: {'Authorization' : 'Token ' + token}
          }
      } catch(error) { return null }
    
    }
    

    Native

    export const getAuthHeader = () => {
      return AsyncStorage.getItem('token')
        .then((token) => {
          if (!token) { return null }
          return {
            headers: {'Authorization' : 'Token ' + token}
          }
        })
        .catch ((error) => null)
    }
    

    also you need to await getAuthHeader in your first method else it will never resolve that value:

    const fetchUserInfo = async (username) => {
      const requestString = apiBaseURL + 'access/user_info/'
      const form = {username: username}
       
      try {
        const response = await axios.post(requestString, form, await getAuthHeader())
        return {
            userInfo: response.data,
            message: null
        }
      } catch(error) {
        return getErrorMessage();
      }
    }