Cannot read property 'showNotification' of undefined - reactjs

i'm using create-react-app with PWA and just can't work notifications api :(
this error:
Cannot read property 'showNotification' of undefined
My code
Notification.requestPermission(function(status) {
console.log("Notification permission status:", status);
});
async function displayNotification() {
if (Notification.permission === "granted") {
await navigator.serviceWorker.getRegistration().then(reg => {
reg.showNotification("Go go")
});
}
}
I didn't understand the error

you cannot both await and use then. You can only use then on promises. And if you await, you resolve your promise.
you can do either :
async function displayNotification() {
if (Notification.permission === "granted") {
const reg = await navigator.serviceWorker.getRegistration();
reg.showNotification("Go go");
}
}
or :
function displayNotification() {
if (Notification.permission === "granted") {
navigator.serviceWorker.getRegistration().then(reg => {
reg.showNotification("Go go");
});
}
}

Related

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

Clearing an item from AsyncStorage - React native

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: '' })
}
})

No function is getting called inside firebase get function

I am trying to write login code, but this firebase get function is refraining me to do so. I am unable to call any function (except alert), within this get function. Navigating to another component also does not work here. I know I have to use async/await keywords but I dont know how to. Can someone please help me with this?
Pasting the code below.
navigate() {
alert("Aya");
}
login() {
const { uname } = this.state;
const { password } = this.state;
var userid = "";
var data;
if (uname && password) {
firebase
.auth()
.signInWithEmailAndPassword(uname, password)
.then(async user => {
userid = await firebase.auth().currentUser.uid;
await db.collection("Users").doc(userid)
.get()
.then(function (doc) {
if (doc.exists) {
data = doc.data();
alert(JSON.stringify(data.role));
if (data.role === "Company Admin") {
logged = true;
alert("Yahoo");
this.navigate();
}
else {
logged = false;
}
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function (error) {
console.log("Error getting document:", error);
});
})
.catch(error => {
alert(error);
this.setState({ error });
});
if (logged) {
alert(logged);
}
else {
alert("Nope");
}
}
else {
alert("Enter all fields data");
}
}
Don't use normal function, you are going to lose the context of this. The this in the callback function is not pointing to your class. So this.navigate() line of code won't work
.then(function (doc) {
As a solution, Use arrow function.
...
.then((doc) => {
...

react redux Promise function to async/await

I have the following redux function adding new user to my database. It works fine but in event i introduce another call in my then, there could be need for extensive catching for everything.
What if we made it into async with try/Catch to handle all our errors ?
I tried a sample of but kept missing something.
Could someone arrange it for me please. Thanks.
export function newUser(values) {
return function(dispatch) {
const promise = axios.post(URL)
dispatch(createAdminUsersRequest(promise));
promise.then(
user => {
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
);
return promise;
};
}
The conversion on promise to async-await is pretty straightforward. Firstly you declare the function as async by adding an async keyword to it. Secondly, you use await on the promise
export function newUser(values) {
return async function(dispatch) {
dispatch(createAdminUsersRequest(promise));
try {
const user = await axios.post(URL);
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
} catch(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
};
}

Resources