react native AsyncStorage not working? - react-native

for setting the item i am using this first code.
console.log(ACCESS_TOKEN);
console.log(typeof(ACCESS_TOKEN));
async function setToken() {
try {
await AsyncStorage.setItem('access_token', ACCESS_TOKEN);
} catch (error) {
console.log("token not set")
}
}
setToken();
for getting the item , i am using this code
componentWillMount(){
async function getToken() {
try {
const value = await AsyncStorage.getItem('access_token');
if (value !== null){
console.log(value);
this.setState({ access_token: value });
}
} catch (error) {
console.log( "Error retrieving data")
}
}
getToken();
the result i am getting in first code is
1a61b72b-ee83-43de-9cf9-3fa270ce694d
string
but getting nothing at console at getting code . why ?

You can try this one:
set item using this
AsyncStorage.setItem('access_token', ACCESS_TOKEN);
get item using this
try {
AsyncStorage.getItem('access_token')
.then((value) => {
if (value) {
// you will get your access_token here
}
}).done();
} catch (error) {
console.log(error); // you will get error here
}

To set the item
AsyncStorage.setItem('access_token', ACCESS_TOKEN)
.then(() => {
//your success code
})
.catch((error) => {
//your failure code
})
To get the item
AsyncStorage.getItem('access_token')
.then(access_token=> {
//you will be getting the access token here
})
.catch(err => {
//handle the error
})

Maybe this is what you intended:
async function getToken() {
try {
const value = await AsyncStorage.getItem('access_token');
if (value !== null){
console.log(value);
this.setState({ access_token: value });
}
} catch (error) {
console.log( "Error retrieving data")
}
}
componentWillMount(){
getToken();
}
If instead your code is getting stuck while working with AsyncStorage, there's a well known bug reproducible only in development: https://github.com/facebook/react-native/issues/12830
They only way to bypass it, afaik, it is just to restart the debugger when you get stuck
Remember that setting state during componentWillMount is not the correct way to do it. You should use the constuctor for that

My answer might not directly apply to your case, But I had the same problem as you did with AsyncStorage and It was getting stuck, so this might help other people.
As stated in this answer:
AsyncStorage only takes string as a value and key.
But I was accidentally giving it null (which as you know is considered an object) so it got stuck. So check if you are passing a string value as both the first and second argument to setItem.

Related

postman req not responding any data even not responding error

Login routes:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({
mobileNo: req.body.mobileNo,
});
if (!user) {
res.status(401).json("You are not registerd");
}
const password = res.body.password;
if (password === user.password) {
return res.status(200).json("You are logged in");
} else {
return res.status(501).json("Naah! wrong pass");
}
} catch {
(err) => {
res.status(500).json(err);
};
}
});
module.exports = router;
index.js:
app.use("/api/auth", authRoute);
import:
const authRoute = require("./routes/auth");
My postman image, I am not getting any result.
Your try-catch syntax is wrong, correct would be
try {
...
} catch(err) {
res.status(500).json(err);
}
With your syntax, when the catch block is reached, the res.status(500).json(err) statement is not executed, therefore the request never comes back.
In your try block, there are 3 responses available. If the first condition in the if block is also executed with another one of the responses in the below if-else condition this problem may occur. Because at a time, sending 2 responses is impossible. Therefore, you should return that response and terminate.
if (!user) {
return res.status(401).json("You are not registered");
}

React Hook does not set on first API call

So I am sure I am messing something up, but I am not super skilled at API.
So I am trying to make an API call to check if the user exists, if user exists then move about business, if not then do other stuff.
So my first call gets the data, and the user DOES exist, the hook is setting to true, however in my log it fails and the next API is ran. However if I do it a 2nd time, it is true...
What am I doing wrong.
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
console.log(checkUser);
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
};
I think the problem here is that setCheckUser(true) is an async operation, so there is no guarantee that the checkUser variable will turn to true right away.
Maybe you can solve this by using a useEffect block like this
//somewhere on the top of your file, below your useState statements
useEffect(()=> {
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
}, [checkUser])
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
};

async function returns promise instead of array

I've been looking for answers on stack overflow but so far nothing is working.
I'm using this function(below) to retrieve a simple array since i want to show its contents in the return() function.
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('FavouritesArray');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
The code does work and it logs the array I want (["Rose","Mojito"]) but i can't figure out how to get the array outside the _retrieveData() function. I've tried returning it (returns a promise) as well as putting it in a global variable and then returning it, but that also just return a promise object.
How do I extract the populated array from this async function?
You can store and retrieve your data like this with AsyncStorage:
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
const getData = async key => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};
then call getData with the key name like you stored your array wherever you want and set the key to a state array.
await getData("yourarraykey")
.then((data) => data)
.then((value) => this.setState({ yourarraystate: value }))
.catch((err) => console.log("AsyncStorageErr: " + err));
after that in this.state.yourarraystate the value of your fetched array will be available.
~Faded

react-native-community/asyncStorage removeItem causes program to behave weirdly

I have this little code snippet executed during the user logout.
async function logoutAction(props) {
removeUser();
props.logoutUser();
}
The function inside removeUser() is as :
export const removeUser = async () => {
try {
await AsyncStorage.removeItem(Constant.storage.user_data);
await AsyncStorage.removeItem(Constant.storage.token);
await AsyncStorage.removeItem(Constant.storage.notification_token);
return true;
} catch (exception) {
return false;
}
}
This clears user related data from local storage.
Similarly, props.logoutUser() is a reference call to reducer which sets loggedIn status to false.
I'm having this issue that if the removeUser() function is called once, the axios http requests do not enter the interceptors anymore and every request catches an error 'undefined'. If this method is removed though, everything works fine.
I can get it to working state then by removing the interceptors once, performing a request and then adding the interceptors again, which I found after hours of here and there.
My interceptors are:
export const requestInterceptor = axios.interceptors.request.use(
async config => {
const token = await getToken();
if (token != '') {
config.headers.Authorization = token;
}
console.log('axios request', config);
return config;
},
error => {
// console.warn('on request error')
return Promise.reject(error);
},
);
export const responseInterceptor = axios.interceptors.response.use(
function(response) {
console.log('axios response', response);
// console.warn('on response success', response.status)
return response;
},
async function(error) {
if (error.response.status === 401) {
//logout user
return;
}
return Promise.reject(error);
},
);
I am using the #react-native-community/AsyncStorage package for maintaining local storage. I suspect that the issue might be in the removeItem method but I'm unsure as the official docs don't contain the removeItem method, or in the interceptor which doesn't seem faulty to me anyways.
What am I doing wrong here?? Please show me some light..
Or maybe try add a await before removeUser(); ?
async function logoutAction(props) {
await removeUser();
props.logoutUser();
}
The issue was quite silly and did not even concern AsyncStorage or removeItem and as Matt Aft pointed out in the comment, it was due to the call for token in the interceptor after it had been removed while logging out. So, replacing
const token = await getToken();
if (token != '') {
config.headers.Authorization = token;
}
by
await getToken()
.then(token => {
config.headers.Authorization = token;
})
.catch(_ => {
console.log('no token');
});
in the interceptor and returning promise from the getToken method did the thing.
Thanks to Matt and 高鵬翔.

got "undefined" when fetching from api other than https://facebook.github.io/react-native/movies.json

I follow this https://facebook.github.io/react-native/docs/network.html#using-fetch to learn how to fetch data from a remote api and it is working great. However, whenever I change the url https://facebook.github.io/react-native/movies.json of that example to another public api, I got "undefined" in my debugger and no data to display. Even the NASA API is returning that.
Any Idea?
const apiHost1 = 'https://facebook.github.io';
const apiHost2 = 'http://countryapi.gear.host';
const apiHost3 = 'https://api.nasa.gov';
export default {
async fectchInitialOrders(){
try {
let response = await fetch(apiHost1 + '/react-native/movies.json');
let responseJson = await response.json();
return responseJson.movies;
} catch (error) {
console.error(error);
}
},
async fectchInitialCountry(){
try {
let response = await fetch(apiHost2 + '/v1/Country/getCountries/');
let responseJson = await response.json();
return responseJson.movies;
} catch (error) {
console.error(error);
}
},
async fectchNasaData(){
try {
let response = await fetch(apiHost3 + '/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo');
let responseJson = await response.json();
return responseJson.movies;
} catch (error) {
console.error(error);
}
}
};
Only the facebook one is returning data
I'm hitting the NASA API from the url that you have used and there is no key called 'movies' in the response. You are trying to access the movies key from the NASA API response which doesn't exist which is why you are probably getting the error.