Home > Software engineering >  Async behaviour when rendering data to headers
Async behaviour when rendering data to headers

Time:01-06

I'm trying to get token from localstorage in my react native application. whenever i run the code below, the token is passed successfully.

const setHeaders = () => {
    const header = {
      headers: {
        Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MWNjZjk2MmYxYjkxZDEzMDQ3NmU3NWEiLCJyb2xlIjoidXNlciIsInVzZXJuYW1lIjoiSnV3b25fSmF2YSIsImVtYWlsIjoiZmFkZXlpYmkyNkBnbWFpbC5jb20iLCJpYXQiOjE2NDEzODA4OTAsImV4cCI6MTY0MTk4NTY5MH0.R_8Yum7s3DuQ7yulSYsNRWRkWGuCTxB_jq39hVn9iQA"
      }
    }
    return header
  }

but the moment I add async to get the code from asyncstorage, it seems not to work but the token is displayed in the console if i want to display it. i'm really confused, somebody should help me out. this is the async code below

const setHeaders = async() => {
    const token = await AsyncStorage.getItem('token');
    console.log('setToken', token) // it sends token to the console but not to the header
    const header = {
      headers: {
        // Authorization: token
        Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MWNjZjk2MmYxYjkxZDEzMDQ3NmU3NWEiLCJyb2xlIjoidXNlciIsInVzZXJuYW1lIjoiSnV3b25fSmF2YSIsImVtYWlsIjoiZmFkZXlpYmkyNkBnbWFpbC5jb20iLCJpYXQiOjE2NDEzODA4OTAsImV4cCI6MTY0MTk4NTY5MH0.R_8Yum7s3DuQ7yulSYsNRWRkWGuCTxB_jq39hVn9iQA"
      }
    }
    return header
  }

Kindly help me please

CodePudding user response:

Kindly send token without saving into variable. I hope it will work.

const setHeaders = async() => {
    
    const header = {
      headers: {
         Authorization: await AsyncStorage.getItem('token');
      }
    }
    return header
  }

CodePudding user response:

you can get the token where you're calling setHeaders and pass it as a parameter, like:

    const token = await AsyncStorage.getItem('token');
    setHeaders(token);

then do it like this:

const setHeaders = (token) => {
    
    const header = {
      headers: {
         Authorization: token;
      }
    }
    return header
 }

Also, make sure token is a string. Hope this works for you!

  •  Tags:  
  • Related