This seems a silly question, so I apologize in advance.
I have a page with several inputs and at the moment, for some reason, I can't just get the new value written in the input, so I can update the state and send this new data. Seems to me there is something wrong in with the onChange function, because I can get the previous state, but not the new value i'm saving on state.
EDIT: The submit button is outside the input form.
Here is the code:
constructor(props) {
super(props)
this.state = {
editMode: false,
data: {
designation: '',
address: '',
description: ''
}
}
}
componentDidMount = () => {
const dataInfo = data.get('url here');//fetching data here
const data = {
designation: dataInfo.designation ,
address: dataInfo.address,
description: dataInfo.description
}
this.setState({
data: data
})
}
handleInput = (e) => {
let value = e.target.value;
let name = e.target.name;
this.setState(
prevState => ({
data: {
...prevState.data,
[name]: value
}
})
);
}
handleFormSubmit = (e) => {
e.preventDefault();
const { data } = this.state;
console.log('hey', data.designation);
this.setState({
editMode: false
})
}
render() {
{!this.state.editMode
? <button onClick={() => this.setState({ editMode: true })}>edit</button>
: <div>
<button
className={styles.buttonMargin}
onClick={() => this.setState({ editMode: false })}>cancel</button>
<button onClick={this.handleFormSubmit}>Guardar</button>
</div>
}
<div>
{this.state.editMode
? <form onSubmit={this.handleFormSubmit}>
<input
type='text'
placeholder='Nome do Campo'
name='designation'
onChange={this.handleInput}
defaultValue={this.state.data.designation}
/>
</form>
: <p> {this.state.data.designation} </p> }
</div>
}
}