i'm use Vue 2 and i wanna detect sockjs errors and show notification.
(Like 'Connection lost','connection timeout' etc. )
I have no idea how to do it
The browser has a built in method called navigator.onLine, which returns either true or false. Now to watch for connection changes you can add an event listener on window,
window.addEventListener('offline', (e) => { console.log('offline'); });
window.addEventListener('online', (e) => { console.log('online'); });
You can incorporate this into a Vue component with something like:
export default {
data() {
return {
online: navigator.onLine
};
},
mounted() {
window.addEventListener("online", this.onchange);
window.addEventListener("offline", this.onchange);
this.onchange();
},
beforeDestroy() {
window.removeEventListener("online", this.onchange);
window.removeEventListener("offline", this.onchange);
},
methods: {
onchange() {
this.online = navigator.onLine;
this.$emit(this.online ? "online" : "offline");
}
}
};
And then use v-if="!online" to selectively render you're offline banner.
Alternatively, take a look at: v-offline, it instead works by pinging an endpoint, which has the advantage of being able to detect when the user is online but with very poor internet connection (loading), however is an overall less efficient approach.
import offline from 'v-offline';
export default {
components: {
offline
},
methods: {
handleConnectivityChange(status) {
console.log(status);
}
}
}
For most sock.js methods, you can get this information from the Event parameter returned by the callback. But for detecting network connection, and other common tasks, it's usually more robust to do natively, as outlined above.
Related
I have a React component, that includes the availability flag of Internet connectivity. UI elements have to be dynamically changed according to state real-time. Also, functions behave differently with the changes of the flag.
My current implementation polls remote API using Axios in every second using interval and updates state accordingly. I am looking for a more granular and efficient way to do this task to remove the 1-second error of state with the minimum computational cost. Considered online if and only if device has an external Internet connection
Current implementation :
class Container extends Component {
constructor(props) {
super(props)
this.state = {
isOnline: false
};
this.webAPI = new WebAPI(); //Axios wrapper
}
componentDidMount() {
setInterval(() => {
this.webAPI.poll(success => this.setState({ isOnline: success });
}, 1000);
}
render() {
return <ChildComponent isOnline={this.state.isOnline} />;
}
}
Edited:
Looking for a solution capable of detecting external Internet connectivity. The device can connect to a LAN which doesn't have an external connection. So, it is considered offline. Considers online if and only if device has access to external Internet resources.
You can use https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event
window.addEventListener('offline', (event) => {
console.log("The network connection has been lost.");
});
and https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event
for checking when you're back online
window.addEventListener('online', (event) => {
console.log("You are now connected to the network.");
});
Method one: Using legacy browser API - Navigator.onLine
Returns the online status of the browser. The property returns a boolean value, with true meaning online and false meaning offline. The property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page. For example, the property should return false when users click links soon after they lose internet connection.
You can add it to your component lifecycle:
Play with the code below using Chrome dev tools - switch "Online" to "Offline" under the Network tab.
class App extends React.PureComponent {
state = { online: window.navigator.onLine }
componentDidMount() {
window.addEventListener('offline', this.handleNetworkChange);
window.addEventListener('online', this.handleNetworkChange);
}
componentWillUnmount() {
window.removeEventListener('offline', this.handleNetworkChange);
window.removeEventListener('online', this.handleNetworkChange);
}
handleNetworkChange = () => {
this.setState({ online: window.navigator.onLine });
}
render() {
return (
<div>
{ this.state.online ? 'you\'re online' : 'you\'re offline' }
</div>
);
}
}
ReactDOM.render(
<App />
, document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
However, I think this isn't what you want, you wanted a real-time connection validator.
Method two: Checking internet connection by using it
The only solid confirmation you can get if the external internet connectivity is working is by using it. The question is which server you should call to minimize the cost?
There are many solutions on the internet for this, any endpoint that responds with a quick 204 status is perfect, e.g.:
calling to Google server (for it being the most battle-tested (?) )
calling its cached JQuery script endpoint (so even if the server is down, you should still be able to get the script as long as you have a connection)
try fetching an image from a stable server (e.g.: https://ssl.gstatic.com/gb/images/v1_76783e20.png + date timestamp to prevent caching)
IMO, if you are running this React app on a server, it makes the most sense to call to your own server, you can call a request to load your /favicon.ico to check the connection.
This idea (of calling your own server) has been implemented by many libraries, such as Offline, is-reachable, and is widely used across the community. You can use them if you don't want to write everything by yourself. (Personally I like the NPM package is-reachable for being simple.)
Example:
import React from 'react';
import isReachable from 'is-reachable';
const URL = 'google.com:443';
const EVERY_SECOND = 1000;
export default class App extends React.PureComponent {
_isMounted = true;
state = { online: false }
componentDidMount() {
setInterval(async () => {
const online = await isReachable(URL);
if (this._isMounted) {
this.setState({ online });
}
}, EVERY_SECOND);
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
return (
<div>
{ this.state.online ? 'you\'re online' : 'you\'re offline' }
</div>
);
}
}
I believe what you have currently is already fine, just make sure that it is calling the right endpoint.
Similar SO questions:
Detect the Internet connection is offline?
Detect network connection in React Redux app - if offline, hide component from user
https://stackoverflow.com/Questions/3181080/How-To-Detect-Online-Offline-Event-Cross-Browser
Setup a custom hook
Setup a hook with the online, offline events. then update a state and return it. This way you can use it anywhere in your app with an import. Make sure you clean up with the return function. If you don't you will add more and more event listeners each time a component using the hook mounts.
const onlineHook = () => {
const {isOnline, setOnline} = React.useState();
React.useEffect(() => {
const goOnline = function(event){
setOnline(true);
});
const goOffline = function(event){
setOnline(false);
});
window.addEventListener('offline', goOffline);
window.addEventListener('online', goOnline);
return () => {
window.removeEventListener('offline', goOffline);
window.removeEventListener('online', goOnline);
}
}, [])
return isOnline
}
To use this just import the above hook and call it like this.
const isOnline = onlineHook(); // true if online, false if not
You can create a component to share between all subcomponents
used:
import React, { useState, useEffect } from "react";
export default function NetworkChecker() {
const [networkStatus, setNetworkStatus] = useState(true)
useEffect(() => {
window.addEventListener('offline', (event) => {
setNetworkStatus(false)
});
window.addEventListener('online', (event) => {
setNetworkStatus(true)
});
return function cleanupListener() {
window.removeEventListener('online', setNetworkStatus(true))
window.removeEventListener('offline', setNetworkStatus(false))
}
},[])
if (networkStatus) {
return <div className={"alert-success"}>Online</div>
} else {
return <div className={"alert-danger"}>Offline</div>
}
}
I'd like to route the user to a certain screen, in case he is not connected to the internet.
I just can't detect if he is connected or not.
I tried this code, but did not work:
async componentWillMount()
{
if (!await NetInfo.isConnected)
{
this.props.navigation.navigate('Saved');
}
}
Any tested solution to suggest?
Try await NetInfo.isConnected.fetch()
ref : https://facebook.github.io/react-native/docs/netinfo.html#isconnected
You can check using NetInfo .
for that you have to add connectionChange event listener like this
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange.bind(this));
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({ isConnected: isConnected }); }
);
and then remove the event listener in componentWillUnmount
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}
And finally the handler method for connection change. I am storing the status in device local storage you can do whatever you want.
handleConnectionChange = (isConnected) => {
if (isConnected) {
//ToastAndroid.show('Data sync in process...', ToastAndroid.SHORT);
AsyncStorage.getItem('offlineData')
.then((json) => JSON.parse(json))
.then((data) => {
console.log(JSON.stringify(data));
});
}
else { ToastAndroid.show('You are offline.', ToastAndroid.SHORT); }
this.setState({ isConnected: isConnected });
}
Don't forget to add NetInfo from react-native :)
Another solution to your case (one without using isConnected property) is to use the object returned from the event handler directly like that:
componentDidMount() {
NetInfo.addEventListener('connectionChange', this.handleNetworkChange);
}
componentWillUnmount() {
NetInfo.removeEventListener('connectionChange', this.handleNetworkChange);
}
handleNetworkChange = (info) => {
if (info.type === 'none') {
this.props.navigation.navigate('Saved');
}
};
According to NetInfo documentation:
connectionChange event fires when the network status changes. The argument to the event handler is an object with keys:
type: A ConnectionType (listed above)
effectiveType: An EffectiveConnectionType (listed above)
The connection type can be one of the following : none, wifi, cellular, unknown.
Ideally you can store this information to your redux store and the listener to a root component.
We had a weird bug when using isConnected similar to the one you mentioned #Gabriel Bleu but for us, the NetInfo.isConnected.fetch() returned false only when the Android device was awake after some period of inactivity.We used it to display offline warning for users, so the warning never left. I found this solution on a Spencer Carli's course and it seems to work better but depending on your needs, you might want to use isConnected combined with the above code.
This is a great example to check online or offline and even you can have connection change information too. Source
NetInfo.isConnected.fetch().then(isConnected => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
NetInfo.isConnected.removeEventListener(
'connectionChange',
handleFirstConnectivityChange
);
}
NetInfo.isConnected.addEventListener(
'connectionChange',
handleFirstConnectivityChange
);
There are two issues with your code currently.
In newer versions of react life-cycle method componentWillMount is deprecated.
Newer versions of react-native have extracted the NetInfo Module out of the core. Use #react-native-community/netinfo instead.
In order to achieve the desired behavior you should do something like this.
import NetInfo from "#react-native-community/netinfo";
class CheckConnection extends Component {
componentDidMount() {
NetInfo.fetch().then(state => {
handleConnectionState(state)
});
}
handleConnectionState(state) {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
... your code to handle the lack of connection
}
}
I currently am using a function on a timed loop to check if a user goes offline:
created() {
setInterval(() => {
this.checkOnline();
}, 30000);
}
Method:
checkOnline(){
this.onLine = navigator.onLine ? true : false;
}
Is there a way I can detect this without using the timer?
Secondly...
I am trying to show an 1 second alert to tell the user they are back online. When this.onLine is true, the div should be hidden. When it is false it should also be hidden, but when it goes from false to true I want to show the div for a second or so and then hide it again. I have tried this with a settimeout and using a watcher but neither give the desired effect.
Edit:
So one method that gets me there is:
data() {
return {
onLine: navigator.onLine ? true : false,
}
}
then a watcher to show the back online message
watch: {
onLine: function (val) {
if(this.onLine === true){
this.showBackOnline = true;
setTimeout(()=>{ this.showBackOnline = false; }, 1000);
}
},
},
Is there a better way than a watcher to achieve this, other than using a dedicated notify plugin?
Is there a way I can detect this without using the timer? Yes. By using the online offline event.
Is there a better way than a watcher to achieve this, other than using a dedicated notify plugin? I think the watcher is the most suitable method here.
demo: https://jsfiddle.net/jacobgoh101/xz6e3705/4/
new Vue({
el: "#app",
data: {
onLine: navigator.onLine,
showBackOnline: false
},
methods: {
updateOnlineStatus(e) {
const {
type
} = e;
this.onLine = type === 'online';
}
},
watch: {
onLine(v) {
if (v) {
this.showBackOnline = true;
setTimeout(() => {
this.showBackOnline = false;
}, 1000);
}
}
},
mounted() {
window.addEventListener('online', this.updateOnlineStatus);
window.addEventListener('offline', this.updateOnlineStatus);
},
beforeDestroy() {
window.removeEventListener('online', this.updateOnlineStatus);
window.removeEventListener('offline', this.updateOnlineStatus);
}
})
you can handle this (update onLine status), just by set arrow function in event listener and set that varible true/false by listener.
window object has online/offline events and you don't need to watch for navigator.online value or set interval to check it. you can just set event listener for it and do something on callback method.
in below code i just change value of my 'isOnLine' variable value and in template show message by v-if directive to user about online/offline.
data() {
return {
isOnLine:navigator.onLine
}
},
mounted() {
window.addEventListener('online', ()=>{this.isOnLine=true});
window.addEventListener('offline', ()=>{this.isOnLine=false});
},
The "Watch" event isn't firing in a Vuex Store. This is pretty basic. It's no more complicated than the example in the help. Does Watch not work in a store?
(All the answers I could find were regarding Angular.)
-Thanks
in store.js
state: {
warningSwitch : false,
}
(...)
watch: {
warningSwitch: function (newState, oldState) {
/* console.log(" Triggered "); */
if(newState){
this.showWarningNotice({title: "Oops", text:"Connection Lost"});
return;
} else {
this.showInfoNotice({title: "Whew...", text:"Connected"});
}
}
},
(...)
mutations: {
setWarningOn(state) {
state.warningSwitchCounter++;
state.warningSwitch = true;
},
}
There is no such thing as a "watch" in a store, as Bert alluded to in the comments.
There are two different approaches that you can take to simulate this behavior, depending on your needs and your architecture.
One, you can watch the store's getters in your component and respond to it there:
watch: {
`$store.getters.warningSwitch`: function (newState, oldState) {
/* console.log(" Triggered "); */
if(newState){
this.showWarningNotice({title: "Oops", text:"Connection Lost"});
return;
} else {
this.showInfoNotice({title: "Whew...", text:"Connected"});
}
}
},
Two, you can actually dispatch additional behavior in the action of the store:
actions: {
setWarningOn: function(context, newState) {
// broadcast event here or commit another mutation
}
}
I'm enjoying working with Meteor and trying out new things, but I often try to keep security in mind. So while I'm building out a prototype app, I'm trying to find the best practices for keeping the app secure. One thing I keep coming across is restricting a user based on either a roll, or whether or not they're logged in. Here are two examples of issues I'm having.
// First example, trying to only fire an event if the user is an admin
// This is using the alaning:roles package
Template.homeIndex.events({
"click .someclass": function(event) {
if (Roles.userIsInRole(Meteor.user(), 'admin', 'admin-group') {
// Do something only if an admin in admin-group
}
});
My problem with the above is I can override this by typing:
Roles.userIsInRole = function() { return true; } in this console. Ouch.
The second example is using Iron Router. Here I want to allow a user to the "/chat" route only if they're logged in.
Router.route("/chat", {
name: 'chatHome',
onBeforeAction: function() {
// Not secure! Meteor.user = function() { return true; } in the console.
if (!Meteor.user()) {
return this.redirect('homeIndex');
} else {
this.next();
}
},
waitOn: function () {
if (!!Meteor.user()) {
return Meteor.subscribe("messages");
}
},
data: function () {
return {
chatActive: true
}
}
});
Again I run into the same problem. Meteor.user = function() { return true; } in this console blows this pattern up. The only way around this I have found thus far is using a Meteor.method call, which seems improper, as they are stubs that require callbacks.
What is the proper way to address this issue?
Edit:
Using a Meteor.call callback doesn't work for me since it's calling for a response asynchronously. It's moving out of the hook before it can handle the response.
onBeforeAction: function() {
var self = this;
Meteor.call('someBooleanFunc', function(err, res) {
if (!res) {
return self.redirect('homeIndex');
} else {
self.next();
}
})
},
I guess you should try adding a check in the publish method in server.
Something like this:
Meteor.publish('messages') {
if (Roles.userIsInRole(this.userId, 'admin', 'admin-group')) {
return Meteor.messages.find();
}
else {
// user not authorized. do not publish messages
this.stop();
return;
}
});
You may do a similar check in your call methods in server.