-
-
Save verticalgrain/195468e69f2ac88f3d9573d285b09764 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react' | |
import { Redirect } from 'react-router' | |
export default class ContactForm extends Component { | |
constructor () { | |
super(); | |
this.state = { | |
fireRedirect: false | |
} | |
} | |
submitForm = (e) => { | |
e.preventDefault() | |
this.setState({ fireRedirect: true }) | |
} | |
render () { | |
const { from } = this.props.location.state || '/' | |
const { fireRedirect } = this.state | |
return ( | |
<div> | |
<form onSubmit={this.submitForm}> | |
<button type="submit">Submit</button> | |
</form> | |
{fireRedirect && ( | |
<Redirect to={from || '/thank-you'}/> | |
)} | |
</div> | |
) | |
} | |
} |
@jjprevite Check your error logs, most of the time you will find the solution there. The problem for you is this line:
const fireRedirect = this.state;
While it should be:
const {fireRedirect} = this.state;
A really great gist. Thank you very much.
thanks it saved me lot of time.
Thanks!!!!
Thanks 😄 🔝
thanks!!!
If you are using redux-saga to manage your side effects and api calls, I would suggest doing this in the saga.
Why? Keeps your component clean and you don't need to keep a state in your component just for the redirect.
I.e. Steps:
- Submit a form
- Dispatch action
- Saga listens for the action, and calls the api
- On success, redirect to wherever you want.
Code:
function* createInvoice(action) {
try {
const response = yield call(axios.post, COMMAND_INVOICES_URL, action.data);
yield put(invoiceCreated());
yield put(push(`/invoice/${response.data}`));
} catch (err) {
yield put(invoiceFailed(err));
}
}
thank you :)
@verticalgrain thank you so much.much applauded.
verticalgrain@ thanks a lot it saved my day
Thanks! Very clean solution!
Thank you!!!!
I think this is another solution. Since there are there elemnet that router provides which are match, location adn history, we may push any route to history. considering rerouting after submiting a form:
{history} = this.props <button onClick={this.onFormSubmit(formValues, history)} )> Submit <button/> ( onFormSubmit(formValues, history) { database.post(formValues) (some codes) history.push('/') } )
nice one
Thanks!! Very useful, helps a lot!!