Reputation: 2015
I'm trying to submit a form in React. This form is connected one
so the form data will be coming as props. What I'm trying to achieve is the form should be autosubmitted when props are different
that means a form should be autosubmitted only once for a single set of props.
I tried adding a condition in componentWillReceiveProps
also where I can determine if the props are different, submit form. Initially, this.props
is undefined in first render of componentWillReceiveProps
class App extends React.Component {
constructor(props) {
super(props)
this.state = { formSubmitted: false }
}
componentWillReceiveProps(nextProps) {
if (this.props.picmonicVideoData.data.signature !== nextProps.picmonicVideoData.data.signature) {
this.setState({formSubmitted: false});
}
componentDidUpdate = () => {
if (!this.state.formSubmitted) {
this.setState({ formSubmitted: true })
document.getElementById('ltiLaunchForm').submit()
}
}
render() {
let renderInputFields = null
if (this.props.videoData.data.hasOwnProperty("signature")) {
renderInputFields = Object.keys(launchData).map((key, i) => {
return (<input type="hidden" name={key} key={i} value={launchData[key]} />)
})
}
return (
<div>
<iframe width="100%" height="430px" frameBorder="0" name="videoIframe"></iframe>
<form name="ltiLaunchForm" id="ltiLaunchForm" method="post" target="target_iframe" encType="application/x-www-form-urlencoded" action={launchUrl}>
{renderInputFields}
<input type="hidden" name="oauth_signature" value={signature} />
</form>
</div>
)
}
}
Any help would be appreciated.
Upvotes: 0
Views: 594
Reputation: 1882
I would advise here to use componentDidUpdate
only as you can easily compare the prevProps
and current props
and perform your submit action. So your code would look something like this:
componentDidUpdate = (prevProps) => {
if (this.props !== prevProps) {
document.getElementById('ltiLaunchForm').submit()
}
}
You will no longer need componentWillReceiveProps
and also avoid using the deprecated lifecycles from React if you are planning to use React 16.3 and above. For detailed explanation, have a look at this link.
Upvotes: 1