I’m not getting the token with Asyncstorage in React Native

Asked

Viewed 234 times

0

I tried to use async/await and it didn’t work either. So I tried with callback. At first I can see the token with console.log(item), however console.log(token) returns undefined.

How can I get the token to be allocated to the variable declared below ?

   let token;
   AsyncStorage.getItem('AUTH', (err, item) => {
     console.log(item)
     token = item;
    
    });
   console.log(token);

1 answer

0


I don’t know what you want to do, but I’ll assume it’s a login using the token.

await AsyncStorage.setItem("save",JSON.stringify(r)) that r is the user login data along with the token and on useEffect (on the same page) I’m taking it like this:

const ttSave = async () => {
  const r = await AsyncStorage.getItem("save");
  const e = JSON.parse(r)//JSON.parse por causa do JSON.stringify
  if(e){
    navigation.navigate('Home', {Home:e})//"Home" seria a pagina seguinte
  }
}

useEffect(()=>{
  ttSave();
}, [])

On the following page you should use the header to get the token, have it with fetch and Axios, in fetch it would be like this

const token = Home.token;// 'Home' é o parametro do usuario

useEffect(()=>{
    fetch('sua url', {
        method: 'get',
        headers: {
            'Content-Type':'application/json',
            "Authorization":`Bearer ${token}`
        }
    })
    .then((response) => response.json())
    .then(res => {setDocs(res)})
    .catch(err=>{})
}, [])

already with the Xios I never tried.

  • I’m getting "can’t find variable Home".

  • if you’re using reactnavigation version 4 it’s like this const id = navigation.getParam('Home');) if it’s version 5 it’s like this ( const { Home } = route.params; )// replace {navigation by route} or you can leave both

Browser other questions tagged

You are not signed in. Login or sign up in order to post.