Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
Toretto Avatar asked Feb 11 '15 11:02

Toretto


People also ask

What are two ways of handling redirect with React router?

Two ways to handle redirecting on a user event such as create, update and delete with React Router.

Can you import redirect from React dom to router?

import { Redirect } from "react-router-dom"; The easiest way to use this method is by maintaining a redirect property inside the state of the component. Whenever you want to redirect to another path, you can simply change the state to re-render the component, thus rendering the <Redirect> component.


2 Answers

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>;
  }
});
like image 50
kulesa Avatar answered Oct 24 '22 19:10

kulesa


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;
like image 39
Dennis Nerush Avatar answered Oct 24 '22 18:10

Dennis Nerush