I have a form in a simple react app. When the form submits, it fires a thunk.
handleSubmit(e) {
e.preventDefault();
this.props.dispatch(loginUser({
username: this.state.username,
password: this.state.password,
history: this.props.history
}));
}
As you can see, I am passing react-router-dom's history to the thunk. Here is the thunk:
export const loginUser = input => dispatch => {
return fetch('xxxxxxxxxx', {
method: 'POST',
body: JSON.stringify({
username: input.username,
password: input.password
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if(!res.ok) {
return Promise.reject(res.statusText)
}
return res.json();
})
.then(token => {
localStorage.setItem('token', token.authToken);
input.history.push('/');
})
.catch(err => console.error(`error: ${err}`));
}
As you can see, if the fetch is successful, I then push to the history.
Is this an anti-pattern? Or is this ok. It works* but I want to know if it's super weird/not recommended