ReactJS + flux - how to handle session-like parameters (pseudoauthorization) - reactjs

Here's the usecase:
I have 2 components in my reactjs application. Both components are fed with data from remote server - via websockets. I don't want my components nor stores to be aware of data source - all websocket logic resides in ActionCrators and something I call SocketListeners.
Here's the example of such a listener:
var listen = function (socket) {
socket
.on(Messages.LIGHTS_CHANGED, function (newConfiguration) {
AppDispatcher.dispatch({
type: LightActionTypes.SUBSTITUTE_LIGHT_CONFIGURATION,
payload: newConfiguration
});
})
};
module.exports = {
listen: listen
};
Since it is a websocket, I need to know the remote url.
I'd like to ask my user to provide this url on my home page - and before that, my components (actually - routes) should not be available and user should be redirected to the page where he is able to specify this URL.
So I need something which looks like a login flow - but instead of login and password, remote url is crucial property here.
How would you manage this session-like state?
I tried something like this:
In my form-like home view I have a function:
handleConnectionConfirmed: function(event) {
event.preventDefault();
ActionCreator.saveRemoteUrl(
this.state.remoteUrl
);
},
which causes to update my ConfigurationStore:
var _lightsUrl = '';
var _temperatureUrl = '';
var ConfigurationStore = {
lightsSocketEndpoint: function () {
return _lightsUrl;
},
temperatureSocketEndpoint: function () {
return _temperatureUrl;
}
};
And then both my components have:
componentWillMount: function () {
ActionCreator.init();
},
Init function:
init: function () {
_socket = WebSocketFactory.lightsWebSocket();
SocketListener.listen(_socket);
},
One last snippet:
lightsWebSocket: function () {
return io.connect(
ConfigurationStore.lightsSocketEndpoint()
)
},
The problem is: as soon as I refresh any page, of course my ConfigurationStore is cleared.
How can I make it somehow persistent without using an external storage?
Also, do you know how can I configure react-router so that it could redirect me to 'login' page when no remote url is specified and user tries to open site where one of those components resides?

Use LocalStorage or SessionStorage. For example:
In your store's constructor do:
_lightsUrl = localStorage.getItem('lightsUrl') || '';
And in the dispatch handler of the store:
_lightsUrl = newLightsUrl;
localStorage.setItem('newLightsUrl');
Here's a nice tutorial which does authentication this way (don't mind the 'Rails' part): http://fancypixel.github.io/blog/2015/01/29/react-plus-flux-backed-by-rails-api-part-2/

Related

Use Service in angular

I use in service in my angular app as follows:
app.service('sharedProperties', function () {
var property;
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
$scope.Somefunc= function(Mname)
{
$http.post("SomeServlet",{
"name": Mname,
}).then(function(response) {
sharedProperties.setProperty(response.data);
window.location = "/blabla/page2.html";
});
};
And in page2 (another conroller) i get the value:
app.controller('controller2', function($scope,$http,sharedProperties) {
$scope.UserProperties = sharedProperties.getProperty();
});
and its doesnt work, always i get undefined.
In order for it to work, you must set the angular routing function which will take care of moving to another page without refreshing your current page (also called SPA - Single Page Application).
Take a look here, at the example in the end of the page there are the different pages and files in the mini system.
I remind you that angular is meant to work with single page applications, so if you refresh the page and change it into another one - You sort of lose the point of using it.

Angular UI Router Reload Controller on Back Button Press

I have a route that can have numerous optional query parameters:
$stateProvider.state("directory.search", {
url: '/directory/search?name&email',
templateUrl: 'view.html',
controller: 'controller'
When the user fills the form to search the directory a function in the $scope changes the state causing the controller to reload:
$scope.searchDirectory = function () {
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email
}, { reload: true });
};
In the controller I have a conditional: if($state.params){return data} dictating whether or not my service will be queried.
This works great except if the user clicks the brower's forward and/or back buttons. In both these cases the state (route) changes the query parameters correctly but does not reload the controller.
From what I've read the controller will be reloaded only if the actual route changes. Is there anyway to make this example work only using query parameters or must I use a changing route?
You should listen to the event for succesful page changes, $locationChangeSuccess. Checkout the docs for it https://docs.angularjs.org/api/ng/service/$location.
There is also a similar question answered on so here How to detect browser back button click event using angular?.
When that event fires you could put whatever logic you run on pageload that you need to run when the controller initializes.
Something like:
$rootScope.$on('$locationChangeSuccess', function() {
$scope.searchDirectory()
});
Or better setup like:
var searchDirectory = function () {
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email
}, { reload: true });
$scope.searchDirectory = searchDirectory;
$rootScope.$on('$locationChangeSuccess', function() {
searchDirectory();
});
Using the above, I was able to come up with a solution to my issue:
controller (code snippet):
...var searchDirectory = function (searchParams) {
if (searchParams) {
$scope.Model.Query.name = searchParams.name;
$scope.Model.Query.email = searchParams.email;
}
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email,
}, { reload: true });
};...
$rootScope.$on('$locationChangeSuccess', function () {
//used $location.absUrl() to keep track of query string
//could have used $location.path() if just interested in the portion of the route before query string params
$rootScope.actualLocation = $location.absUrl();
});
$rootScope.$watch(function () { return $location.absUrl(); }, function (newLocation, oldLocation) {
//event fires too often?
//before complex conditional was used the state was being changed too many times causing a saturation of my service
if ($rootScope.actualLocation && $rootScope.actualLocation !== oldLocation && oldLocation !== newLocation) {
searchDirectory($location.search());
}
});
$scope.searchDirectory = searchDirectory;
if ($state.params && Object.keys($state.params).length !== 0)
{..call to service getting data...}
This solution feels more like a traditional framework such as .net web forms where the dev has to perform certain actions based on the state of the page. I think it's worth the compromise of having readable query params in the URL.

How to redirect after success from ajax call using React-router-component?

I am building a application using Facebook flux architecture of React JS. I have build the basic part of app where I have a login form. I am fetching the the result from node server to validate user at the store, I am getting the result from server, Now I got stuck that how can I redirect the user to home page after success.
I have read about the react router component and I am able to redirect at the client side but not able to redirect at the time of fetching result from ajax in Store. Please help me.
You need to use the transitionTo function from the Navigation mixin: http://git.io/NmYH. It would be something like this:
// I don't know implementation details of the store,
// but let's assume it has `login` function that fetches
// user id from backend and then calls a callback with
// this received id
var Store = require('my_store');
var Router = require('react-router');
var MyComponent = React.createClass({
mixins: [Router.Navigation],
onClick: function() {
var self = this;
Store.login(function(userId){
self.transitionTo('dashboard', {id: userId});
});
},
render: function() {
return: <button onClick={this.onClick}>Get user id</button>;
}
});
It worked for me when I added to the react element properties a require for the router and used the router like this:
// this is the redirect
this.context.router.push('/search');
// this should appear outside the element
LoginPage.contextTypes = {
router: React.PropTypes.object.isRequired
};
module.exports = LoginPage;
This should work
var Store = require('Store');
var Navigatable = require('react-router-component').NavigatableMixin
var LoginComponent = React.createClass({
mixins: [ Navigatable ],
onClick: function() {
Store.login(function(userId){
this.navigate('/user/' + userId)
}.bind(this));
},
render: function() {
return <button onClick={this.onClick}>Login</button>;
}
});

Which one should I use? Backbone.js Router.navigate and window.location.hash

I began learning Backbonejs recently, by reading a book. and I feel a little bit confuse about this issue.Here is a Router:
define(['views/index', 'views/login'], function(indexView, loginView) {
var SelinkRouter = Backbone.Router.extend({
currentView: null,
routes: {
'home': 'home',
'login': 'login'
},
changeView: function(view) {
if(null != this.currentView)
this.currentView.undelegateEvents();
this.currentView = view;
this.currentView.render();
},
home: function() {
this.changeView(indexView);
},
login: function() {
this.changeView(loginView);
}
});
return new SelinkRouter();
});
and this is the boot method of a application:
define(['router'], function(router) {
var initialize = function() {
// Require home page from server
$.ajax({
url: '/home', // page url
type: 'GET', // method is get
dataType: 'json', // use json format
success: function() { // success handler
runApplicaton(true);
},
error: function() { // error handler
runApplicaton(false);
}
});
};
var runApplicaton = function(authenticated) {
// Authenticated user move to home page
if(authenticated) window.location.hash='home';
//router.navigate('home', true); -> not work
// Unauthed user move to login page
else window.location.hash='login';
//router.navigate('login', true); -> not work
// Start history
Backbone.history.start();
}
return {
initialize: initialize
};
});
My question is about the runApplication part. The example of the book that I read passed router into module just like this, but it used window.location.hash = "XXX", and the router wasn't touched at all.
I thought the "navigate" method would make browser move to the page I specified, but nothing happened. Why?
And for the best practice sake, what is the best way to achieve movement between pages(or views)?
thanks for any ideas.
You could also use the static method to avoid router dependency (while using requirejs for instance).
Backbone.history.navigate(fragment, options)
This way, you just need :
// Start history
Backbone.history.start();
// Authenticated user move to home page
if(authenticated)
Backbone.history.navigate('home', true);
// Unauthed user move to login page
else
Backbone.history.navigate('login', true);
According to the documentation, if you also want to call the function belonging to a specific route you need to pass the option trigger: true:
Whenever you reach a point in your application that you'd like to save
as a URL, call navigate in order to update the URL. If you wish to
also call the route function, set the trigger option to true. To
update the URL without creating an entry in the browser's history, set
the replace option to true.
your code should look like:
if(authenticated)
router.navigate('home', {trigger: true});
Once your router is created, you also have to call
Backbone.history.start();
Backbone.history.start([options])
When all of your Routers have
been created, and all of the routes are set up properly, call
Backbone.history.start() to begin monitoring hashchange events, and
dispatching routes.
Finally the runApplication logic will be something similar to this:
var runApplicaton = function(authenticated) {
var router = new SelinkRouter();
// Start history
Backbone.history.start();
// Authenticated user move to home page
if(authenticated)
router.navigate('home', true);
// Unauthed user move to login page
else
router.navigate('login', true);
}

What to be done to prevent the router URL being used directly on the address bar by user?

Have done some working samples using Backbone Router, but is there a way to protect the routes being used directly on the address bar? And also when the user press the back button on the browser, the routes doesn't get cleared and creates issues. What is the best solution for this?
I think I see what you're saying - you want to force the user to enter your site through a certain (home) page. Is that correct?
This is useful, for example, when you're building a mobile-optimized-web-app, and you always want users to enter through a splash screen. What I'll do is set a 'legitEntrance' property to my router, and check for it on every route, as so:
APP.Router = Backbone.Router.extend({
legitEntrance: false,
// Just a helper function
setLegitEntrance: function() {
this.legitEntrance = true;
},
// Send the user back to the home page
kickUser: function() {
this.navigate("home", {trigger:true});
},
routes : {
...
},
// Example router function: Home page
routeToHome: function() {
this.setLegitEntrance();
var homeView = APP.HomeView.extend({ ... });
homeView.render();
},
// Example router function: some other internal page
routeToSomeOtherInternalPage: function() {
if(!this.legitEntrance) {
this.kickUser();
return;
}
var someOtherInternalView = APP.SomeOtherInternalView.extend({
...
});
someOtherInternalView.render();
}
....
});
I'm sure this code could be cleaned up some, but you get the general idea. Hope it helps.

Resources