0

I got an api request using axios coming from my backend server. I want to save the bearer token to the device storage or local storage. But when i do console.log for the bearer token, it seems not working because what i get is something like a promise.

Here is my method

import {AsyncStorage, Alert} from 'react-native';
export default function login(email,password,setLoading){

   console.log('Loading...')
   setLoading(true)

    axios.post('http://52.74.70.6/api/auth/login',{
       email: email,
       password: password
   },{
       headers:{
        Accept: 'application/json',
        'Content-Type': 'application/json',
       }
   })
    .then((res)=>{
        setLoading(false)
        AsyncStorage.setItem('bearer_token', res.data.bearer_token);
        console.log(AsyncStorage.getItem('bearer_token'))
        console.log('Loading Finished')
    }).catch((err)=>{
        setLoading(false)
        console.log(err)
        AlertErr()
    })
}

What I got is

Loading...

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

Loading Finished

3 Answers 3

1

You can use async/await with try/catch which makes it more readable. Also, you will need to await the request to AsyncStorage as it returns a promise.

import { AsyncStorage, Alert } from "react-native";
export default async function login(email, password, setLoading) {
  console.log("Loading...");
  setLoading(true);
  const url = "http://52.74.70.6/api/auth/login";
  const data = {
    email: email,
    password: password,
  };
  const headers = {
    Accept: "application/json",
    "Content-Type": "application/json",
  };
  try {
    const response = await axios.post(url, data, { headers: headers });
    setLoading(false);
    await AsyncStorage.setItem("bearer_token", res.data.bearer_token);
    console.log(await AsyncStorage.getItem("bearer_token"));
    console.log("Loading Finished");
  } catch (err) {
    setLoading(false);
    console.log(err);
    AlertErr();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for this. This is the one i currently followed. how do i use the bearer_token in all of my request when i finished login?
Well, you can add Authorization in your headers like this { headers: {"Authorization" : `Bearer ${token}`} } , token = await AsyncStorage.getItem("bearer_token") . Thanks for the vote @Vince.
1

Since it's "Async" have you tried to add await before it

 await AsyncStorage.setItem("bearer_token", res.data.bearer_token);
 console.log(await AsyncStorage.getItem('bearer_token'))

or just return the promise in your promise chain


then((res)=>{
        setLoading(false)
        await AsyncStorage.setItem('bearer_token', res.data.bearer_token);
        return AsyncStorage.getItem('bearer_token')
    })
.then(token => console.log('token', token)

Comments

1

As the name suggests, AsyncStorage is Asynchronous. both setting an item and reading an item from AsyncStorage are asynchronous so you cannot immediately read the results of you insersion. Accoreding to the docs, In order to log it you could

AsyncStorage.setItem('bearer_token', res.data.bearer_token).then(() => {
    AsyncStorage.getItem('bearer_token').then(console.log)
});

Comments

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.