React hook cleanup when refreshing the page - reactjs

I have an app built in React using hooks that when closed needs to notify the server. I tried doing it using the following approach:
function onUnload() {
if (roomID !== "")
endGame(roomID, dispatch);
}
useEffect(() => {
return onUnload;
},[])
Here, endGame is a function that performs a HTTP request to the backend. But when refreshing the page to emulate a user closing the app, the request never reaches the server, meaning that the cleanup function doesn't get executed. Any ideas on what is wrong?
Thanks in advance

Refreshing the page is not same as component unmount. When you refresh the page, the React state is reset as React solely works on the current client session and refresh is equivalent to resetting it. What you are lloking for might be the onunload event. Try this:
window.onbeforeunload = function(e) {
return onUnload();
};

Related

Browser.addEventListener of cordoba not fire setState within listenerFunc

I am using React with Ionic to build an app. I have a method that calls Browser.open to open InAppBrowser for external URL. I am adding a listener when the browser closes with Browser.addEventListener and effectively the functenerFunc runs but for some reason, the function does not fire some setState and dispatch called within that function.
const [someBoolean, setSomeBoolean] = useState<boolean>(false);
const openWindows = (url) => {
Browser.addListener('browserFinished', () => {
// This console log fires when the browser is closed
console.log('start');
// Those methods does not fire when the browser is closed
setSomeBoolean(true)
dispatch(someImportedReactAction('RS2'));
console.log('finish')
Browser.removeAllListeners()
})
Browser.open({
url: url
})
}
As you can see in the code above, the first console.log fires with no problem, but after that, it seems that the function stops and nothing happened. setSomeBoolean and the dispatch do not fire.
Any ideas why?

How to listen to navigate event?

Problem: I would like to use callback functions based on changes in href when user navigates within the same page.
For example, i would like to use a callback when a user navigates out of the component (changing href from localhost:3000/user to localhost:3000/about)
I've tried
popstate (which works when using forward/backward)
unload(works when i refresh)
pagehide/pageshow did not seem to respond at all.
visibilitychange fired whenever i moved out of the tab, but it was not what I was looking for.
You can use the useEffect cleanup function to trigger logic when the component unmounts.
useEffect(() => {
effect
return () => {
cleanup
}
}, [input])

How to get state from one react component to another?

I'm new in ReactJS, that's why i'm here.
I created a component 'Login' and have variable 'isAuthenticated' in this.state.
After user login I change value of this variable to true and my app redirect user to home page.
In main page I must to check 'isAuthenticated' value and rerender component depends on it.
But it's not working. I got error: "Unable to get property 'setState' of undefined or null reference".
Please help me how to fix it all.
If you are not using something like Redux for your state management I suggest you use the localStorage of the browser to store that value for isAuthenitcated. Something like
localStorage.setItem('isAuthenticated', true); - on login
then in the other component you can use:
localStorage.getItem('isAuthenticated'); - to figure out what you want to show
remember to set isAuthenticated to false on logout as well!
localStorage.setItem('isAuthenticated', false); - on logout
I hope you will be having a login function like below
function login(){
doLogin().then(function(data){
this.setState({isAuthentcated: true});
});
}
Bind the login function to the component using ES6 Arrow function like this
login = () => {
doLogin().then((data) => {
this.setState({isAuthentcated: true});
});
}

Redirect on asynchronous Call back with AngularJS in Ionic mobile app

I have a mobile app created with Ionic and angularJS.In the app i'm using websql database to save data locally in device.when call my function(which is with a callback) i need move to another page(homepage).this is not happening with callback.can someone help me to figure this out.(Im using apprey to build my application)
Below is my javascript function with call back function as websql is asynchronous by its nature.
var logbool;
ValidateUserLocalCookie(success,function(isLogged)
{
console.log("Logged"+isLogged);
**Apperyio.navigateTo("Home", {});///---this function should redirect to home**
});
and below is the websql function.
function ValidateUserLocalCookie(success,callbackFunc)
{
logbool=false;
db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(function(tx)
{
var boole=false;
tx.executeSql('select * from Userlog;',[],function(tx,table){
console.log(table.rows.length);
if(table.rows.length>0){
logbool=true;
callbackFunc(logbool);
}
else{
logbool=false;
callbackFunc(logbool);
}
});
});
}
By default, Ionic apps use the ui-router. Leverage that. You should have a list of states predefined in your router code.
Once that's done, simply inject the $state service into your controller. Inside of the callback, use it to set your state. Here is some code that does something similar.
function saveClass() {
$log.log('Saving class.');
ClassService.save(vm.class)
.then(function () {
$state.go('tabsController.classes');
})
.catch(function (err) {
$log.log(err);
});
}
My ClassService calls an asynchronous database function, which I have exposed as a promise. You can also use a callback. Upon completion of the save, I call $state.go(<state-name>); In the event of an error, I remain on the same page.

Login ajax request Flux React?

How can I do
after login form submit (React Component)
using flux structure
ajax request that provides response ?
Can you provide some example ?
Basically you need to make an Ajax request, and then create success/error handlers. Inside those handlers, you will create actions to inform your stores of the result. It's probably a good idea to have an AppStore or SessionStore or something that will hold the data related to the current user and the auth token. Your controller-views can listen to that store and render their children when the current user becomes authenticated.
Here's how i made:
When my component bootstraps, I fire an INIT action to the Store which initially gets the datas i need. Here's the simplified data flow
After login my Library component is rendered so i need to initialize the data (books, users etc..)
Library:
componentDidMount: function() {
Store.addChangeListener(this._onChange);
Actions.initialize();
},
As you can see, when my component did mount, i fired a new action, and my store will handle this action.
Store:
switch(action.actionType) {
case Constants.INIT:
_init().done(function() {
Store.emitChange();
});
break;
I'm calling the private function _init() which will return a promise object. When the promise is Fulfilled the Store is ready to emit it's change event.
In _init I'm simulating some async data loads, thats why i made the promise, here it is:
function _init() {
var loadBooksDeferred = new jQuery.Deferred(),
loadUsersDeferred = new jQuery.Deferred(),
loadCategoriesDeferred = new jQuery.Deferred(),
stateReadyDfd = new jQuery.Deferred();
_loadBooks(loadBooksDeferred);
_loadUsers(loadUsersDeferred);
_loadCategories(loadCategoriesDeferred);
jQuery
.when(loadBooksDeferred, loadUsersDeferred, loadCategoriesDeferred)
.then(stateReadyDfd.resolve, stateReadyDfd.reject);
return stateReadyDfd;
}

Resources