0

I have little problem with my component and action. Inside my component i pass (login,password) to authorize. Then in action creator i make post request to my server, and when status i 200 and want to push user to other path for example "/" but this wont work.

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import * as actions from '../../actions';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

class Signin extends Component{

constructor(props){
super(props);
this.state= {};
this.onSubmit = this.onSubmit.bind(this);
}

renderField(field){
    return(
    <div className="form-group">
        <label>{field.label}</label>
        <input
            className="form-control"
            type="text"
            {...field.input}
            />

    </div>
    );
}

onSubmit(e){
    e.preventDefault();
    let {username,password} = this.state;
    this.props.actions.signinUser({username,password});
    this.setState({
        username: '',
        password: ''
    })
}




render(){
    let {username,password} = this.state;


    return(
        <form onSubmit={this.onSubmit}>

            <Field
                label="Username:"
                name="username"
                component={this.renderField}
                onChange={e => this.setState({username: e.target.value})}
            />
            <Field
                label="Password:"
                name="password"
                component={this.renderField}
                onChange={e => this.setState({password: e.target.value})}
            />
            <button action="submit" className="btn btn-primary"> Sign In 
</button>
        </form>

    );
 }
}


function mapStateToProps(state) {
return { form: state.form };
}

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

Signin = connect(
mapStateToProps,
mapDispatchToProps 
)(Signin);

export default reduxForm({
form: 'signin'
})(Signin);

import axios from 'axios';



export function signinUser({username,password}){
return function(dispatch){

    axios.post('http://localhost:8585/auth', { username, password})
    .then(response => {

          this.context.history.push('/'); or history.push('/'); 
            also tried  `this.props.history`?

        localStorage.setItem('token', response.data.token);
        console.log("ok");

      })
      .catch(() => {
        console.log("not ok");
      });
    };

}

class App extends Component {
 render() {
return (
  <Router>
      <div className="container">
      <Header />
      <Route exact path="/" component={Home} />
      <Route path="/signin" component={SignIn} />
      <Route path="/about" component={About} />
    </div>
  </Router>
 );
 }
}

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware } from 'redux';

import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import reducers from './reducers';
import reduxThunk from 'redux-thunk'

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);


ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>

, document.getElementById('root'));
registerServiceWorker();

Any ideas? i using react router v4.

I tried many things, (create own history), pass function in props from component to action. And still dont work..

  • Where have you written history.push()?? – Narasimha Reddy - Geeker Oct 09 '17 at 10:45
  • sorry, i edit post. i try to push after localstorage.setkey – ktostamtakidziwny Oct 09 '17 at 10:52
  • I don't think so, that you can use history object inside axios api call. it is not a preferable way too. Instead you can do it it In `componentWillRecieveProps`. you can check for token in `localStorage` if it's present just redirect from there using this.props.history.push(). You can any of the following way to redirect in react-router 4. https://stackoverflow.com/questions/42123261/programmatically-navigate-using-react-router-v4 – Narasimha Reddy - Geeker Oct 09 '17 at 11:01
  • @NarasimhaReddy it is good way of doing that? Check in localStorage for key and if key is there i push user to / ? – ktostamtakidziwny Oct 09 '17 at 11:56

1 Answers1

0

You have to put everything in BrowserRouter. Check below Code.

  <Provider store={configureStore()}>
    <BrowserRouter>
        <LocaleProvider locale={enUS}>
            <Route path='/' component={App} />
        </LocaleProvider>
    </BrowserRouter>
</Provider>

You will get history and use push() by using this.props.history.push('you_path');

Check React Router Documentation.

Mushfiq
  • 713
  • 1
  • 8
  • 37