skip to Main Content

I am using Expo to Login User with Facebook, I am receiving token with Graph Api but when I try to add the token in Async Storage it is not working.

Please see the code below:

async logIn() {
 try {
  const {
   type,
   token,
  } = await Facebook.logInWithReadPermissionsAsync('<APP_ID>', {
  permissions: ['public_profile'],
 });

 if (type === 'success') {
  // Get the user's name using Facebook's Graph API
   fetch(`https://graph.facebook.com/me?access_token=${token}`)
  .then((res) => res.json())
  .then((tokenKey) => AsyncStorage.setItem('userToken',tokenKey))
  .then(() => this.props.navigation.navigate('App'))
  } else {
    // type === 'cancel'
   }
 } catch ({ message }) {
  alert(`Facebook Login Error: ${message}`);
 }
}

I am receiving the token when I console it

 fetch(`https://graph.facebook.com/me?access_token=${token}`)
  .then((res) => res.json())
  .then((tokenKey) => console.log('userToken',tokenKey))
  .then(() => this.props.navigation.navigate('App'))

Please help, I am new to react native and asynchronous programming in JavaScript. TIA 🙂

3

Answers


  1. Chosen as BEST ANSWER

    Sorry folks the problem was from my side, I was trying to store an object directly into Async Storage, whereas Async Storage only accepts values in String format. I used

    .then((tokenKey) => AsyncStorage.setItem('userToken',JSON.stringify(tokenKey)))
    

    and it fixed the problem,Thanks all for your help


  2. Are you getting token from AsyncStorage with getItem?

    AsyncStorage.getItem('userToken').then((token) => {
                this.setState({hasToken: token !== null,localToken : token})
            });
    
    Login or Signup to reply.
  3. Try this if you want to get item from AsyncStorage

    AsyncStorage.getItem('userToken', (error, result) => {
        if (result) {
          //result
        }
        else {
          //error
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search