'React native async storage token goes missing after going back a screen and coming back auth is failing
I am new to react native, bear with me. when i click on categories(A) i navigate to new screen containing different subcategories(B) i am using get token on this page(B) and sending a request to fetch i can fetch successfully display sub categories. when i go back to screen A from there and clicking on categories again it's a error auth is failing in api call the token is missing, if i do this in a few minutes gap it works fine , just when i do immediately token is missing
useEffect(()=>{
(async()=>{
const token=await getToken()
setUserLToken(token)
})()
}
)
Solution 1:[1]
You can save the token in the constant file, and whenever you call the API fetch the token from that file. so it will never give you the token missing file error.
Asyncstorage takes some time to get the value that's why you getting the token missing issue.
Create a File like AppManager.js and create prams in this file like below:
export var ConstantId =
{
accessToken: '',
};
Now, whenever you set a token in Asyncstorage also save the token in the AppManger file like below:
import {ConstantId} from './AppManager';
ConstantId.accessToken = token;
Now, whenever a token is required just get it from the AppManger file, like below:
import {ConstantId} from './AppManager';
const token = ConstantId.accessToken ;
One more thing, every time you launch the app just check if the token is stored in Ascynstorage or not if the token is there then fetch the token and store it in AppManager.js file from App.js file only, like below
useEffect(() => {
let token = await AsyncStorage.getItem('token');
if (token != null) {
ConstantId.token = token;
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |