I have an async function that checks the permission status in a device. This is the function:
notificationsAllowed = async () => {
const allowed = await requestNotifications(['alert', 'sound']).then((res) => {
if (res.status == "granted") {
return true;
}
return false;
});
return allowed;
}
allowed is boolean, but when I try to use this function (for example, to set a switch to true or false) I get an object for some reason.
This is how I try to use it:
const allowed = NotificationsManager.getInstance().notificationsAllowed().then((res) => {
return res;
});
const [isEnabled, setIsEnabled] = useState(allowed);
It seems like allowed is of type Promise<boolean> but I can't use async await because it is inside a functional component.
You should use useEffect for something like this.
const [isEnabled, setIsEnabled] = useState(false);
useEffect(() => {
NotificationsManager.getInstance().notificationsAllowed().then((res) => {
setIsEnabled(res);
});
}, []);
This is not how async functions or await work. Normally, with Promises (like requestNotifications), you run it, it does its work in the background and then it runs the .then() function when it's done (at some point in the future).
await does what it says, and waits for the Promise to resolve/finish before continuing on. You don't need .then() here, since you are waiting for it to finish in a different way.
notificationsAllowed = async () => {
const allowed = await requestNotifications(['alert', 'sound']);
return allowed.status === "granted"
};
But now notificationsAllowed is an async function. So you either need to use .then() which runs it in the background or use await to wait for notificationsAllowed to complete.
const allowed = await NotificationsManager.getInstance().notificationsAllowed();
const [isEnabled, setIsEnabled] = useState(allowed);
Or you need to use a callback, which will run at some point in the future and not let you return a value:
NotificationsManager.getInstance().notificationsAllowed().then(allowed => {
const [isEnabled, setIsEnabled] = useState(allowed);
});