Tikkes Tikkes - 2 months ago 6
React JSX Question

React reroute on ajax call

I have an authentication side on my application working using

passport
.
This will give me a
403
back when the user does not have access to a specific route, this includes api routes too.

i.e.

app.use('/api/calendar', passport, authorize([roles.SOME_ROLE]), calendar);


later I call this
api/calendar
route to get a calendar like so:

var getAll = function () {
return $.get(routes.MAIN + routes.GET_CALENDAR)
.error(function(error) {
//this is where I am stuck
});
}


How do I, when I reach the error part, redirect to another route?

Note that this file is a service file, the
getAll
method gets called from the
React
component:

loadCalendar: function () {
var self = this;
calendarService.getAll()
.then(function (data) {
self.props.load(data);
});
},


I know I could do it in this
loadCalendar
function but that would mean that any time I do a call to any service I need to include an
error
block and I'd prefer to have it centralized in the
service
files.

Answer

So for people trying to figure this one out, I found it some time ago.

first, you need to have a Router in your React component.

var withRouter = require('react-router').withRouter;
var SomeComponent = withRouter(
    React.createClass({
        PropTypes: {
        },
        .........

Next, we setup our service to be able to call the Router:

var router = null;
var setRouter = function (routerToSet) {
    router = routerToSet;
}
//..... other stuff

module.exports: {
//.....
setRouter: setRouter
}

Now we can call - on an Ajax error - the router to redirect

function handleErrorResponse(error, router) {
    if(error.status == statusCodes.UNAUTHORIZED) {
        if(router) {
            router.replace(unauthorizedPath);
        }
        else {
            toastr.error("Router not defined", "CRITICAL ERROR");
            throw new Exception("CRITICAL ERROR: Router not defined");             
        }
    }
    else {
        return error; 
    }
}


function handleError(error) {
    return handleErrorResponse(error, router);
}

var myAjaxCallToHandle= function () {    
    return $.ajax({
        url: routes.where_ever,
        data: JSON.stringify(data),
        method: "POST",
        contentType: "application/json"
    })
    .error(handleError);
}

The only thing left to do is, in the component, couple the Router

//.........
        getInitialState: function () {
            unitPlantService.setRouter(this.props.router);
        }
//.........
Comments