OneSignal net::ERR_CONNECTION_RESET - reactjs

I have a reactjs app which is connected to a oneSignal app for web notifications.
here are my config for oneSignal
function OneSignalInit(appid) {
await OneSignal.init({
appId: appid
});
OneSignal.showSlidedownPrompt();
}
function initOneSignal(appId) {
/* Call push notification */
try {
return OneSignalInit(appId);
} catch (error) {
return console.log(error);
}
}
function App() {
useEffect(() => {
if (!hasPlayerId) {
hasPlayerId = true;
initOneSignal(process.env.REACT_APP_NOTIFICATION).then(async () => {
OneSignal.getUserId((userId) => {
if (userId) {
console.log('🔔 ~ Player ID', userId);
}
});
});
}
}, []);
return (<div>OneSignal App</div>)
}
when i run it the app is connected and i receive the notifications fine, but after awhile I get this error
GET https://onesignal.com/api/v1/apps/APP_ID/icon net::ERR_CONNECTION_RESET
after that i can't get any notifications until i clear the browser cache and reload the page.
Any idea why it happens and how to restart the connection without having to clear the browser cache?

Related

Having to press log out twice to actually destory my user's session - react + express

I've got a react front end that performs some actions. The relevant axios requests look like so:
const login = async () => {
await Axios.post('http://localhost:8000/login', {
username: username,
password: password,
}).then((response) => {
console.log("login response: ", response);
window.location.href = "http://localhost:3000/";
}).catch(err => {
alert(err.response.data);
});
};
// run on first render to see if user session is still active - remove console log later
useEffect(() => {
Axios.get("http://localhost:8000/isLoggedIn").then((response) => {
console.log("isLoggedIn resonse: ", response);
if (response.data.loggedIn === true) {
setLoginStatus(`Logged in as ${response.data.user}`);
}
})
}, [])
const Logout = async () => {
try {
await Axios.get('http://localhost:8000/logout').then((response) => {
console.log(response);
window.location.href = "http://localhost:3000/login";
}).catch(err => {
alert(err);
});
} catch (error) {
alert(error)
}
};
I keep having to press log out twice to actually log my user out. The logout route runs before the "isLoggedIn" route, according to my network tab. And it's successful, too. Here are the isLoggedIn and logout routes in my express backend:
export function isLoggedIn( req: any, res: any) {
if (req.session.user) {
// if our session already has a user, send true to the frontend
// frontend runs this get login on first render, so will have user data if cookie has not expired.
res.send({loggedIn: true, user: req.session.user})
} else {
res.send({loggedIn: false});
}
}
export function logout(req: any, res: any) {
if (req.session) {
req.session.destroy( (err: any) => {
if (err) {
res.status(400).send('Unable to log out');
} else {
res.send("Logout successful");
}
});
} else {
res.end();
}
}
I'm getting a successful logout. I just cannot figure out why I need to hit the logout button twice on the frontend to actually destroy the session and log the user out? Is there something timing related that I may be missing here?

How to integrate Phantom wallet in react project?

I actually desire to integrate phantom wallets into my custom hand website. Since I'm new to the web 3, I've just used Metamask and am unsure of what Solana and Phantom Wallets are.
Write a provider and then wrap your _app with this provider:
import {
ConnectionProvider,
WalletProvider,
} from '#solana/wallet-adapter-react'
import { WalletModalProvider } from '#solana/wallet-adapter-react-ui'
import { PhantomWalletAdapter } from '#solana/wallet-adapter-wallets'
import { useMemo } from 'react'
const WalletConnectionProvider = ({ children }) => {
const endpoint = useMemo(() => 'https://api.devnet.solana.com', [])
const wallets = useMemo(() => [new PhantomWalletAdapter()], [])
return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={wallets} autoConnect>
<WalletModalProvider>{children}</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
)
}
export default WalletConnectionProvider
or you manually check for window.solana the way you connect to window.ethereum
const isWalletConnected = async () => {
try {
const { solana } = window;
if (solana) {
if (solana.isPhantom) {
console.log("phantom wallet found");
// When using this flag, Phantom will only connect and emit a connect event if the application is trusted. Therefore, this can be safely called on page load for new users, as they won't be bothered by a pop-up window even if they have never connected to Phantom before.
// if user already connected, { onlyIfTrusted: true }
const response = await solana.connect({ onlyIfTrusted: false });
console.log(
"public key",
response.publicKey.toString()
);
setWalletAddress(response.publicKey.toString());
} else {
alert("Please install phantom wallet");
}
}
} catch (error) {
console.log(error);
}
};

Getting c.trim error form google oauth2 web client requestAccessToken function

I am using google Oauth2 client script but in that "requestAccessToken" function geving me 2 error. See on bellow image
Here I am loading the 'https://accounts.google.com/gsi/client' script dynamically and after it been loaded I am createing a tokenClient by using initTokenClient funciton.
When user click on the button I am checking is token is allready avaiable or not if not then I am sending a request for google auth popup
tokenClient.current.requestAccessToken({ prompt: 'consent' });
But this requestAccessToken funciton giveing me a error called c.trim() is not a funciton. As per as I found it's comming form the internal implementation of this funciton
I am also getting another CORS error in the same place.
Reproduce Link: https://codesandbox.io/s/nostalgic-ives-wngw3v?file=/src/Picker.jsx
Error Image
import React, { useEffect, useRef, useState } from 'react';
import loadScript from 'load-script';
const GOOGLE_INDENTITY_URL = 'https://accounts.google.com/gsi/client';
const clientId = '865996907937-t2ca9nu95hv87f204t11gikb2rqm3s4v.apps.googleusercontent.com';
const scope = ['https://www.googleapis.com/auth/drive.readonly'];
let scriptLoadingStarted = false;
export default function TryPicker() {
const tokenClient = useRef();
const isGoogleAuthReady = () => {
return !!window.google?.accounts?.oauth2;
};
const doAuth = () => {
console.log('yea', tokenClient.current, tokenClient.current.requestAccessToken);
// // Use Google Identity Services to request an access token
tokenClient.current.requestAccessToken({ prompt: 'consent' });
};
const onChoose = () => {
if (!isGoogleAuthReady()) {
return null;
}
doAuth();
return undefined;
};
const onAuthLoad = () => {
tokenClient.current = window.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope,
callback: async response => {
if (response.error !== undefined) {
throw response;
}
console.log(response);
},
});
};
useEffect(() => {
if (isGoogleAuthReady()) {
// google api is already exists
// init immediately
onAuthLoad();
} else if (!scriptLoadingStarted) {
// load google api and the init
scriptLoadingStarted = true;
loadScript(GOOGLE_INDENTITY_URL, onAuthLoad);
} else {
// is loading
}
});
return (
<div>
<button className="text-darker" onClick={onChoose} type="button">
Get access token
</button>
</div>
);
}
As mentioned by yash, it's probably cuz you are using array. This is how used it for multiple scopes.
scope: 'https://www.googleapis.com/auth/user.birthday.read \
https://www.googleapis.com/auth/profile.agerange.read \
https://www.googleapis.com/auth/user.gender.read',
```

Gapi Error in while using youtube data api in reactjs app

I have build up a project using Next.js. Here I have wanted to implement a feature using the YouTube Data API. The feature is when the user clicks the youtube connect button, a pop-up window opens and authenticates the user. After the authentication, the YouTube Data API gives a response which contains the basic info the user's channel. Sometimes it has worked fine. But, sometimes it has shown the following error:
Here is my code:
import { Fragment, useEffect, useContext } from "react";
import {gapi} from "../common/api";
import { GOOGLE_CLIENT_ID } from "../../helpers/Constants";
import { AthleteContext } from "../../context/AthleteContextProvider";
import { Button, message } from "antd";
import AthleteProfileService from "../../services/AthleteProfileService";
const YouTubeConnect = () => {
const athleteContext = useContext(AthleteContext);
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey(GOOGLE_API_KEY);
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API");
execute();
},
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.channels.list({
"part": "snippet,contentDetails,statistics",
"mine": true
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", JSON.parse(response.body));
athleteContext.invokeYoutubeInfo(response.body);
AthleteProfileService.connectSocialAccount({
attrName: "youtube",
attrValue: JSON.parse(response.body).items[0].id
}).then(res => {
message.success("Youtube profile link added!");
athleteContext.setProfileUpdateStatus(true);
}).catch(err => {
console.log(err);
athleteContext.setProfileUpdateStatus(false);
})
},
function(err) { console.error("Execute error", err); });
}
function executeFinal() {
authenticate().then(() => {
loadClient();
})
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: GOOGLE_CLIENT_ID});
});
return (
<Fragment>
{/* <button onClick={() => authenticate().then(() => loadClient())}>auth</button> */}
<Button onClick={() => executeFinal()}>Connect</Button>
</Fragment>
)
}
export default YouTubeConnect;
I have tried some solutions. But, it still shows the error. Please tell me where is the problem.
Thanks in advance.

How service worker works?

I am newbie to progressive web apps. I have gone through this amazing tutorial and setup for my react PWA(progressive web) app.
Now this is my serviceworker.js file
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === '[::1]' ||
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
checkValidServiceWorker(swUrl);
navigator.serviceWorker.ready.then(() => {
});
} else {
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log('New content is available; please refresh.');
} else {
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
fetch(swUrl)
.then(response => {
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
But could not able to understand how it works? Can anyone please help what register, unregister and other function do here?
Please help!!!
Based from the documentation:
A service worker is a type of web worker. It's essentially a
JavaScript file that runs separately from the main browser thread,
intercepting network requests, caching or retrieving resources from
the cache, and delivering push messages.
From your sample code above, you are using react framework to build PWA with create-react-app. It will eliminates all of that by allowing developers to build React apps with little or no build configuration.
To Build a realtime PWA with React:
The service worker code basically registers a service worker for
the React app. We first check if the app is being served from localhost via the isLocalhost const value that will either return a truthy or falsy value. The register() function helps to register the
service worker to the React app only if its in a production mode and
if the browser supports Service workers.
The registerValidSW() function that will register the valid service worker and responsible for the state if it is installed.
The checkValidServiceWorker() will check if service worker can be found. This will ensure service worker exists, and that we really are getting a JS file.
The unregister() function
helps to unregister the service worker.

Resources