I'm new to Redux, and I really don't have much time to spend researching, so I would appreciate if you could help me out. So basically I have a React component where I authenticate a user with an HTTP request to a backend. When I get the response back, I want the data to be saved in a Redux store so I can access it on other components/routes. How could this be done? Thank you.
This is my component:
class Register extends Component {
constructor(props) {
super(props);
this.state = {
errorMessage: null,
user: null
};
}
register = (event) => {
event.preventDefault();
console.log(event.target.email.value);
let errorMessage = null;
if (!event.target.name.value) errorMessage = 'Numele este obligatoriu.';
else if (!event.target.email.value)
errorMessage = 'Email-ul este obligatoriu.';
else {
const body = {
name: event.target.name.value,
email: event.target.email.value,
password: event.target.password.value,
confirmPassword: event.target.confirmPassword.value
};
return axios
.post('http://localhost:5000/api/v1/auth/register', body)
.then((response) => {
console.log(response);
this.setState({ // Instead of this, the user should be stored using Redux
user: response.data.data.user
});
})
.catch((error) => {
this.setState({ errorMessage: error.response.data.message });
});
}
this.setState({ errorMessage });
};
render() {
return (
<div className="register-page">
<form onSubmit={this.register}>
<h3>Cont nou</h3>
<input type="text" placeholder="Nume" name="name" />
<input type="text" placeholder="E-mail" name="email" />
<input type="password" placeholder="Parola" name="password" />
<input
type="password"
placeholder="Confirmă parola"
name="confirmPassword"
/>
<span className="error-message">{this.state.errorMessage}</span>
<input type="submit" value="Trimite" name="submit" />
</form>
</div>
);
}
}
export default Register;