Giter VIP home page Giter VIP logo

Comments (4)

ajeetvarma avatar ajeetvarma commented on May 27, 2024 1

@bernabe9 , Thanks a lot for your suggestion .

I have resolve my problem after making few changes in my code. I used localStorage instead of sessionService. My code was like following line..

             return authentication.login(user.email, user.password).then(response => {
                   localStorage.setItem('userToken', response.data.token);
                   localStorage.setItem('userEmail', response.data.email);
                   localStorage.setItem('userAuthenticated', response.data.authenticated);
                   browserHistory.replace('/dashboard');
                });

And this code working very fine.

Even sessionStorage is also working in place of localStorage.

Again very much thanks a lot to you ..

from redux-react-session.

bernabe9 avatar bernabe9 commented on May 27, 2024

@ajeetvarma which function doesn't behave as you expect? checkAuth in the onEnter of react-router?
Which version of react-redux-session and react-router are you using?

Also, if you could show me the part of the code that fails will be very helpful

from redux-react-session.

ajeetvarma avatar ajeetvarma commented on May 27, 2024

My package.json like this..

      dependencies": {
         "jquery": "^3.1.1",
         "react": "^15.4.2",
         "react-dom": "^15.4.2",
         "react-loader": "^2.4.0",
         "react-redux": "^5.0.2",
         "react-router": "^3.0.2",
         "react-router-redux": "^4.0.8",
         "redux": "^3.6.0",
         "redux-devtools-extension": "^2.13.0",
          "redux-react-session": "^1.1.0",
         "redux-thunk": "^2.2.0"
       }

My Routes configuration like this..

         import React, { Component } from 'react';\
         import { Router, browserHistory, Route, IndexRoute } from 'react-router';
         import { createStore, applyMiddleware } from 'redux';
         import thunk from 'redux-thunk';
         import reducer from './reducers';
         import { composeWithDevTools } from 'redux-devtools-extension';
         import { Provider } from 'react-redux';
         import { syncHistoryWithStore } from 'react-router-redux';
         import { sessionService } from 'redux-react-session';

         const store = createStore(
           reducer,
                 composeWithDevTools(
                 applyMiddleware(thunk)
              )
             )
        const history = syncHistoryWithStore(browserHistory, store);
        sessionService.initSessionService(store);
       
       class App extends Component {
              render() {
                    return (
                         <Provider store={store}>
                            <Router history={history}>
                                   <Route path="/" component={Index}>
                                        <IndexRoute to="/Index"/>
                                    </Route>
                                    <Route path="/product/:productId" component={SingleProduct} />
                                    <Route path="/profile" onEnter={sessionService.checkAuth} component={Profile} />
                                     <Route path="/login" component={Login} />
                                     <Route path="/logout" component={Logout} />
                                     <Route path="*" component={NotFoundPage} />
                            </Router>
                         </Provider>
                       );
                    }
                 }
             export default App;

api.js is like this..

                import axios from 'axios' ;

                const authentication = {
                            login (email, password) {
                                    const response = axios.post('http://localhost:8000/project/loginapi/' + email + '/password/' + password);
                            return new Promise(resolve => setTimeout(resolve(response), 1000));
                        },

                       logout () {
                            return new Promise(resolve => setTimeout(resolve, 1000));
                        },
                  }

SessionAction.js like this..

                    import { browserHistory, router } from 'react-router';
                    import { sessionService } from 'redux-react-session';
                    import authentication  from './Api.js';
                    
                   export const loginUser = (user) => {
                       return () => {
                             return authentication.login(user.email, user.password).then(response => {
                             sessionService.saveSession(response.token)
  .                          then(() => {
                                  sessionService.saveUser(response.data)
                                  .then(() => {
                                   browserHistory.replace('/profile');
                              });
                           });
                         });
                      };
                    }; 

                    export const logout = () => {
                        return () => {
                               return authentication.logout().then(() => {
                                     sessionService.deleteSession();
                                     sessionService.deleteUser();
                                      browserHistory.replace('/login');
                                 }).catch(err => {
                             throw (err);
                           });
                         };
                     };

Login.js is like this ..

                    import React, { Component, PropTypes } from 'react';
                    import { connect } from 'react-redux';
                    import { bindActionCreators } from 'redux';
                    import * as sessionActions from './SessionActions';
                    inport Input from './Input.js';

                    class Login extends Component {
                             constructor(props, context) {
                                           super(props, context);
                                           this.state = {
                                              user: {
                                                     email: '',
                                                    password: ''
                                                 }
                                             };

                                      this.onSubmit = this.onSubmit.bind(this);
                                      this.onChange = this.onChange.bind(this);
                                   }

                               onSubmit() {
                                  const { user } = this.state;
                                  const { loginUser } = this.props.actions;
                                  loginUser(user);
                               }

                                 onChange(e) {
                                            const { value, name } = e.target;
                                            const { user } = this.state;
                                            user[name] = value;
                                            this.setState({ user });
                                   }
                                 render() {
                                         const { user: { email, password } } = this.state;
                                              return (
                                                    <div>
                                                       <h3>LOGIN</h3>
                                                      <Input
                                                              name="email"
                                                              value={email}
                                                              label="Email"
                                                              type="email"
                                                             onChange={this.onChange}
                                                      />
                                                   <Input
                                                            name="password"
                                                            value={password}
                                                            label="Password"
                                                            type="password"
                                                            onChange={this.onChange}
                                                   />
                                                 <button onClick={this.onSubmit} type="submit">Submit</button>
                                          </div>
                                       );
                                    }
                               }
                                    const { object } = PropTypes;

                                    Login.propTypes = {
                                            actions: object.isRequired
                                      };

                                    const mapDispatch = (dispatch) => {
                                              return {
                                                  actions: bindActionCreators(sessionActions, dispatch)
                                                 };
                                        };

                                  export default connect(null, mapDispatch)(Login);

My Input.js is also just like your package file .. After authentication is completed when i check the inspect element redux options i found token and another results are coming in session storage and also authenticated and checked are displaing as true but it is seeming that the code

                            browserHistory.replace('/profile');

is not working. Also when i am refreshing the same page after authentication the session storage values are deleted automatically i. e. it become logout automatically ..

Thanks a lot for your response and hopes for help from you ..

from redux-react-session.

bernabe9 avatar bernabe9 commented on May 27, 2024

@ajeetvarma did you try to put a brake point before the redirect line?

Just like this:

sessionService.saveSession(response.token)
.then(() => {
  sessionService.saveUser(response.data)
  .then(() => {
    debugger; // -------> add this line
    browserHistory.replace('/profile');
  });
});

Then try to login with the inspector open and check if the code stops there. If the code stops there it means that the problem surely is in the Profile component and is not in redux-react-session.

In the case that it doesn't stops there you can try to add a catch statement and print the error.
Just like this:

 sessionService.saveUser(response.data)
  .then(() => {
    browserHistory.replace('/profile');
  }).catch((err) => console.log(err));

If you use the user information saved with sessionService.saveUser in the Profile make sure that you are passing well the response.data in the following line: sessionService.saveUser(response.data).

Let me know if it works, I hope to be helpful

from redux-react-session.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.