Clearing an item from AsyncStorage - React native - reactjs

I'm new to react native currently i'm working on a project that needs to update a specific value in async storage. I tried by clearing an item from Asyncstorage using this code await AsyncStorage.removeItem(key); but when i used it console throws an error like this 'await' is only allowed within async functions . But i'm using an async function
const getExceedCountData = async () => {
const token = await AsyncStorage.getItem("#userToken")
const exceedcount = await AsyncStorage.getItem("#exceedCount")
if(!exceedcount){
try {
setLoading(true)
axios
.get(constants.BASE_URL + "getexceedcount?token=" +token)
.then(response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
.catch(error => {
console.log(error);
});
} catch(error) {
console.log(error);
}
}else{
setExceedCount({ value:exceedcount, error: '' })
}
}
I don't know why this issue occured. Any help is appreciable.

You need to notate the function as async.
.then(async (response) => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})

The scope of the function inside .then is not declared as async. This should fix your problem:
.then(async response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
} catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})

Related

How to test useEffect with Auth api and state inside

useEffect(()=>{
Auth.currentAuthenticatedUser().then((user) => {
setUser(user)
setIsLoading(false)
if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
navigate('/ForceChangePassword')
}
else{
navigate('/App')
}
}).catch(error => {
console.log('isCurrentAuthenticatedUser- ',error)
setUser(null)
setIsLoading(false)
})
});
We can simply mock the Auth.currentAuthenticatedUser() part.
For example:-
Auth.currentAuthenticatedUser = jest.fn().mockImplementation(()=>Promise.resolve({challengeName: 'NEW_PASSWORD_REQUIRED'}))
If someone wants to cover the catch block then:-
Auth.currentAuthenticatedUser = jest.fn().mockImplementation(()=>Promise.reject())

Not able to get the response code in react js axios

Here is my common method for post:
export const post = (url: string, param: any) => {
const CancelToken = axios.CancelToken; // axios cancel request
const source = CancelToken.source();
post.prototype.source = source;
return axios.post(url, qs.stringify(param), { cancelToken:
source.token }).then((resp) => resp);
};
Here is my post method:
const postMyMethod = async () => {
await postMd(params)
.then((response: any) => {
console.log(response) // in response not getting status code
})
};
Below is the error handling code, how to get the response status code(ex: 200, 400...):
axios.interceptors.response.use(
function (response) {
if (response && response.data && response.data.Code && response.data.Message) {
message.error(response.data.Message);
response.data = null;
}
return response;
},
function (error) {
if (error.response && error.response.data && error.response.data.Code && error.response.data.Message) {
message.error(error.response.data.Message);
} else {
message.error('Unknown error, please check your network ~');
}
return error;
}
);
Finally if I do:
console.log(response)
Getting: Error: Request failed with status code 400
How to get the status code to do the if condition in the postMyMethod()?
I want to do like this in the postMyMethod(). How to achieve this?
if(response.status === 200){
// do something
}
if (respone.status === 400){
// do something
}
The error is because you are not using a catch() block in your postMyMethod function. You should add it so it will handle any error response. It will look something like this:
const postMyMethod = async () => {
await postMd(params)
.then((response) => {
console.log(response)
}).catch((err) => {
console.log(err.response.statuscode);
});
};
If response code 400 is something specific you want to handle differently in your function, your catch() block will be:
const postMyMethod = async () => {
await postMd(params)
.then((response) => {
console.log(response)
}).catch((err) => {
if (err.response.statuscode == 400) {
console.log(err);
} else {
console.log("something else");
}
});
};
You can read more about the catch() method here.
Finally got it:
.then((response: any) => {
console.log(response.response.status);
console.log(response.response.data);
})
or need to add below code under function error > if condition
return error.response;
Now getting the response status and failure data.

How do I get the HTTP response code from a successful React query?

How do I get the status code from a successful React query?
This is my custom hook:
const validateIban = async (accountId, encodedIban) => {
await axios
.post(`${CUSTOMER_PORTAL_API}/policy/accounts/${accountId}/iban/${encodedIban}`)
};
export function useValidateIban(accountId) {
return useMutation(encodedIban => validateIban(accountId, encodedIban));
}
And this is where I use the hook with mutate:
const validateIbanQuery = useValidateIban(accountId)
validateIbanQuery.mutate(encodeURIComponent(iban), {
onSuccess: () => {
******HERE I WANT THE STATUS CODE (204, 202 e.g.)******
},
onError: (error) => {
if (error.response.status === 400) {
....
}
if (error.response.status === 403) {
....
}
}
})
The first parameter of the onSuccess callback is the AxiosResponse:
axios.post("/api/data", { text }).then(response => {
console.log(response.status)
return response; // this response will be passed as the first parameter of onSuccess
});
onSuccess: (data) => {
console.log(data.status);
},
Live Demo

Axios promise will never resolve

For the life of me, I can never get my Axios.post promise to resolve.
I know that my front end and backend are perfectly connected.
Try/catch blocks to return the resolved promise haven't worked either.
No matter what I do, I can never get inside of my promise.then() function. What am I doing incorrectly in my backend file?
CODE THAT HASN'T WORKED TO RESOLVE THE PROMISE
async handleDateSubmit() {
let resolvedPromise = await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
resolvedPromise
.then(response => {
//I can never get to here.
console.log("Made it inside");
})
.catch(err => console.log(err));
}
//---attempt two----//
async getResolvedPromise() {
try {
return await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
} catch (error) {
console.log(error);
}
}
async handleDateSubmit() {
let resolvedPromise = this.getResolvedPromise();
//work with resolvedPromsie
}
CURRENT CODE
//------------send_info.js front end file----------//
handleDateSubmit() {
Axios.post('http://localhost:3001/get_number_of_dates_from_email', {
email: this.state.user_email_m
})
.then((response) => {
//I can never get to here.
console.log("Made it inside");
})
.catch(err => console.log(err));
}
//---------------server.js backend file---------------//
router.route('/get_number_of_dates_from_email').post(function (req, res) {
//"user_email" is correct in my schema model and "req.body.email" is always what it should be
User.findOne({ user_email: req.body.email }, (err, foundUser) => {
console.log("Inside of findOne()");
if (err) {
return res.send(err);
}
else {
let numDates = foundUser.dates_list.length;
//I always get here and numDates is always correct
console.log("Number of dates: ", numDates);
return res.json({ "numDates": numDates }); //Should I be using res.send()?
}
});
});
It seems like you're confusing promises and resolved promises at times in your code
// Attempt one
async handleDateSubmit() {
try {
let resolvedPromise = await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
// Here resolvedPromise as stated by its name is not a promise anymore, thus you can't use .then()
// You can directly work with resolvedPromise as it contains the response.
} catch (e) {
console.error(e)
}
}
// Attempt two
async getResolvedPromise() {
try {
// Here you're returning the resolved promise, but the async await syntax turn your function into an AsyncFunction object
// This type of function will wrap the return value in a promise if it's not one
return await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
} catch (error) {
console.log(error);
}
}
async handleDateSubmit() {
// Thus you need to await the result of your function
let resolvedPromise = await this.getResolvedPromise();
}

Persisting data if none exists for a certain key using AsyncStorage

I'm trying to set up a function where I first check to see if I have a value for a certain key, and if I do not, I use the axios library to get a value from the web and persist it as that key's value instead. Here is my code:
async getName() {
try {
const value = await AsyncStorage.getItem('dummy'); //the value should be a JSON object
if (value !== null){
return value.name;
}
else {
axios.get('https://api.github.com/users/dummy')
.then(function (response) {
console.log(response);
try {
await AsyncStorage.setItem('dummy', 'dummyval');
} catch (error) {
console.log(error);
}
return(response.name);
})
.catch(function (error) {
console.log('Error fetching name: ' + error.response);
});
}
} catch (error) {
console.log(error);
}
I'm pretty new to React Native, so I'm sure this looks like a mess. I know I must be doing something wrong because I keep getting a syntax error on the second use of await. Does anyone know how to properly structure these calls?
You need to declare axios's success handler using async keyword. In your code, you have written like .then(function (response), this should be changed to .then(async function (response).
Consider following changes.
async getName() {
try {
const value = await AsyncStorage.getItem('dummy'); //the value should be a JSON object
if (value !== null){
return value.name;
}
else {
axios.get('https://api.github.com/users/dummy')
.then(async function (response) {
console.log(response);
try {
await AsyncStorage.setItem('dummy', 'dummyval');
} catch (error) {
console.log(error);
}
return(response.name);
})
.catch(function (error) {
console.log('Error fetching name: ' + error.response);
});
}
} catch (error) {
console.log(error);
}
}
Hope this helps!

Resources