can help me not update the decorator's properties until after another dispacth takes the value. I do not know what's wrong.
@connect((store) => {
return {
adminLogin:store.adminLogin.error
};
})
class Login extends React.Component {
constructor(props){
super(props)
this.state={
errors:{},
user:{
email:'',
password:''
}
}
store.subscribe(()=>{
console.log(this.props.adminLogin)
this.setState({
errors:store.getState().adminLogin.error
})
})
this.home = this.home.bind(this);
this.onChange = this.onChange.bind(this);
this.processForm = this.processForm.bind(this);
}
home(){
this.props.history.push('/')
}
onChange(e){
const user = this.state.user;
const name = e.target.name;
user[name] = e.target.value;
this.setState({
user
})
}
processForm(event) {
event.preventDefault();
// create a string for an HTTP body message
const email = encodeURIComponent(this.state.user.email);
const password = encodeURIComponent(this.state.user.password);
const formData = 'email=${email}&password=${password}';
this.props.dispatch(postLogin(formData))
}
render() {
return (<LoginCompo
onSubmit={this.processForm}
home={this.home}
user={this.state.user}
onChange={this.onChange}
errors={this.state.errors}
/>);
}
}
export default Login;
export function postLogin(formData) {
return function(dispatch){
const xhr = new XMLHttpRequest();
xhr.open('post', '/auth/login');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status === 200) {
localStorage.setItem('admin',xhr.response.token)
dispatch({type:'SAVE_TOKEN',token:xhr.response.token})
} else {
dispatch({type:'ERROR_LOGIN',error:xhr.response.errors})
}
};
xhr.send(formData);
}
}
export default function reducer(state={
token:'',
error:{},
}, action) {
switch (action.type) {
case "SAVE_TOKEN": {
return {...state, token: action.token}
}
case "ERROR_LOGIN":{
return {...state, error:action.error}
}
}
return state
}