Display the user-disconnected page in NextJs - next.js

I'm looking for a way to show to user, like WhatsApp web, a page that when connection is poor or user has no internet, says "Your internet connection is down".
How to do this in Next Js ?

You have to add this custom hook to your _app.js file :
function useNetwork(){
const [isOnline, setNetwork] = useState(window.navigator.onLine);
useEffect(() => {
window.addEventListener("offline",
() => setNetwork(window.navigator.onLine)
);
window.addEventListener("online",
() => setNetwork(window.navigator.onLine)
);
});
return isOnline;
};
Add your logic :
const isOnline = useNetwork();
////////////////////////
useEffect(()=>{
if(!isOnline){
// show your going offline message here
}
},[isOnline])

Related

How do I fix firebase auth/netwok-request-failed when opened by social media browsers?

I recently had a bug to solve for a customer on my webapp. It is givng a
Firebase: Error(auth/network-request-failed)
However I also realize upon selecting 'Ok' on the alert, the browser redirects the user to login with their account, however has a my FIREBASE_AUTH_DOMAIN - {projectID}.firbaseapp.com .
This only occurs when user visit the login/signUp link via social media browser.
So I changed the signInWithPopUp -> signInWithRedirect.
And now I still get the error if I am redirected to the login/signUp page. How I do fix this?
const loginGoogle = async () => {
closeSnackbar();
const provider = new GoogleAuthProvider();
signInWithRedirect(auth, provider)
.then(() => {
createUserDoc(); //creates a userProfile document
enqueueSnackbar(
`Welcome ${
!auth.currentUser.displayName ? "" : auth.currentUser.displayName
}`,
{ variant: "success" }
);
})
.catch((error) => {
alert(error.message);
});
router.push(redirect || "/shop");
};

How to add custom error message notification in login page

I have started integrating the react-admin page, In the login page, I'm trying to manage the error message in the auth provider. I'm not able to get the error message to display in the notification .any one please help.
login: ({ username, password }) => {
const request = { 'email': username, 'password': password}
return axios.post(process.env.REACT_APP_URL+`/login`, request).then(response => {
let result = response.data;
if(result.success){
} else {
console.log(response.data);
throw new HttpError(result.message);
}
// localStorage.setItem('username', username);
return Promise.resolve();
}).catch(error => {
return error;
});```
You can use the useNotify function from react-admin to render custom notifications.
//Import the notification
`import {useNotify} from 'react-admin';`
...
...
//Place this line in your component.
`const notify = useNotify();`
...
...
//Place this wherever you want to show notification
`notify('Message of Notification');`
//For error notifications
`notify('Error Notification','error);`
More on https://marmelab.com/react-admin/Actions.html
Edit: on reading the comment realised that this requires custom error messages.
https://marmelab.com/react-admin/doc/2.8/Translation.html
You would need to replace the messages from 'ra-language-english' with your own.
import React from 'react';
import { Admin, Resource } from 'react-admin';
import englishMessages from 'ra-language-english';
const englishCustomMessages = englishMessages;
englishCustomMessages.ra.auth.sign_in_error = 'Your Custom Message goes here';
const messages = {
en: englishCustomMessages,
}
const i18nProvider = locale => messages[locale];
const App = () => (
<Admin locale="en" i18nProvider={i18nProvider}>
...
</Admin>
);
export default App;
If you want to customize more notifications look at this file:
https://raw.githubusercontent.com/marmelab/react-admin/89ac783fd9f961401d1c2e8d4ca4965053ed1d21/packages/ra-language-english/index.js
Don't import directly as you may not stay updated with the changes in react-admin. Always override only the required changes.

How to correctly set up foreground notifications using react-native-firebase v5?

We have a react-native app that runs its notifications through FCM with the following environment:
react-native: 0.59.10,
react-native-firebase: 5.5.6
All the configs have been set up, certificates provisioned, etc. Until the very present time, notifications have been working like a clock, but recently we stopped receiving notifications in the foreground.
Here's the NotificationsManager code:
import firebase from 'react-native-firebase';
const CHANNEL = 'default';
...
const localNotificationListener = React.useRef();
const notificationOpenListener = React.useRef();
const onTokenRefreshListener = React.useRef();
const receiveForegroundPN = (n) => {
const notification = new firebase.notifications.Notification()
.setNotificationId(n.notificationId)
.setTitle(n.title)
.setSubtitle(n.subtitle)
.setBody(n.body)
.setData(n.data);
if (Platform.OS === 'android') {
notification
.android.setChannelId(CHANNEL)
.android.setSmallIcon('ic_launcher');
}
firebase.notifications().displayNotification(notification);
};
React.useEffect(() => {
const channel = new firebase.notifications.Android.Channel(
CHANNEL,
'Bank Notifications',
firebase.notifications.Android.Importance.Max,
).setDescription('*****');
firebase.notifications().android.createChannel(channel);
localNotificationListener.current = firebase.notifications().onNotification(receiveForegroundPN);
notificationOpenListener.current = firebase.notifications().onNotificationOpened(openNotification);
onTokenRefreshListener.current = firebase.messaging().onTokenRefresh((fcmToken) => {
registerToken({
device_token: fcmToken,
});
});
runFlow();
return () => {
localNotificationListener.current();
notificationOpenListener.current();
onTokenRefreshListener.current();
};
}, []);
Notifications work just fine on both platforms while the app is in the background, but never show when the app is in the foreground.
I've tried setting show_on_foreground: "true", but that didn't help. Actually, I tried logging anything in the receiveForegroundPN method but it was never called, i.e. it looks like notifications are never received from firebase when app is running.
What might be the issue here and possible solutions to make notifications work?
Update
All of a sudden, within the hour of posting this, iOS started to receive foreground notifications. Android still doesn't work, yet it used to.
I am having a similar issue as well.. ,
The onNotification method doesn't get trigerred so i tried the onMessage method instead which seems to work for foreground.
firebase.messages().onMessage(msg => {
// ... your code here
});
Iterating on Amr's answer.
As per documentation, you must hook into firebase's callbacks to get notified when a push notification is received in foreground.
From that point you can decide how to handle the message.
The simplest way is to display an alert Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage)); or
You can use another library to display a local notification. Here is an example using react-native-notifications library:
// Just call the hook in some root component that's always present
export const useDisplayRemoteNotifications: () => void = () => {
useEffect(() => {
return messaging().onMessage(async remoteMessage => {
Notifications.postLocalNotification({
title: remoteMessage.notification?.title || '',
body: remoteMessage.notification?.body || '',
fireDate: dayjs().add(1, 'second').toDate(), // one second later
});
});
}, []);
};

javascript ream.close() not closing, stopped

I am using Realm Database to store data for page navigation in my react native application.The below method stops working after I invoke realm.close()
Can you please suggest me what might be the issue.
export const getStorageProtags = () => {
return Realm.open({
schema: [ProtagsSchema]
}).then(realm => {
const protags = realm.objects('Protags');
realm.close();
return protags[0];
});
}

Can home_url() be dynamically passed to a theme built with React?

Testing out and building a WordPress theme in React I've typically seen the URL hard coded in a componentDidMount like:
class Home extends React.Component{
componentDidMount(){
const API_URL = 'https://foobar/wp-json/wp/v2/posts/';
this.serverRequest = $.get(API_URL, function (result) {
this.setState({
result:result,
loaded:true
});
}.bind(this));
}
}
export default Home;
but I was curious to know if there was a way in the functions.php -> Home.js I can pass home_url, in the example https://foobar, without having to manually modify Home.js?
Per querying the site with the paramters [wordpress][reactjs] I've been unable to find if this is asked. Can this be done or a way to pass the wp-json/wp/v2 to React dynamically?
Edit:
There appears to be some confusion in what I'm trying to do. If you were to use Axios with React instead of fetch, example from Using Axios with React, you'd have to use a GET to pull the WP_JSON from WordPress. The example link uses:
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
the URL, https://jsonplaceholder.typicode.com/users, is static and every time I were to load this theme to a new site, the URL will need to be changed. How can I change the present URL to match the theme's hosted URL dynamically so that if the domain were to change from:
https://jsonplaceholder.typicode.com/users
to
https://jsonwinners.typicode.com/users
I wouldn't have to do it manually.
Judging from what you're trying to achieve, i would rather use document.location.origin
however, to answer your question, you CAN get php to send a variable to javascript....
Method 1 (dirty) - custom script tag in the head
add_action('wp_head', function(){
echo '<script>var MY_OBJ.users_url = "'.home_url('/users').'";</script>';
});
and then in your js file...
componentDidMount() {
axios.get(MY_OBJ.users_url)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
Method 2 - localized script
wp_enqueue_script( 'home-js', get_theme_file_uri('/assets/js/Home.js'), array(), '1.0', true );
$my_php_array = array(
'home_url' => home_url('')
'users_url' => home_url('/users')
);
wp_localize_script( 'home-js', 'MY_OBJ', $my_php_array );
and then in your js file...
componentDidMount() {
axios.get(MY_OBJ.users_url)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}

Resources