Hi everyone,
I make a function to remove the empty array elements but it’s not working properly. I have to click on the submit button two times for it to be working (and I want to be working on one click).
So here is my code :
FormTeacher.jsx
const initState = {
reponses: [
{
id : 0,
reponse: ""
},
{
id : 1,
reponse: ""
},
{
id : 2,
reponse: ""
},
{
id : 3,
reponse: ""
}
],
}
class FormTeacher extends React.Component {
constructor(props) {
super(props);
this.state = initState
}
removeEmptyAnswer = () => {
const valueToRemove = "";
this.setState(prevState => {
const reponses = prevState.reponses.filter(answerItem => answerItem.reponse !== valueToRemove);
console.log("remove", reponses);
return {reponses};
});
}
render() {
const{updateFormTeacher} = this.props;
const{reponses} = this.state;
const displayAnswers = reponses.map((answerItem, index) => {
<MDBInput
key={answerItem.id}
value={answerItem.reponse}
name="reponses"
type="text"
id={'displayAnswers'+answerItem.id.toString()}
label="reponse"
required
onChange={this.handleAnswers(index)}>
<div className="valid-feedback">Looks good!</div>
</MDBInput>
});
return (
<MDBRow>
<MDBCol md="4" style={{ maxWidth: "8rem" }}>
<div>R: {displayAnswers}</div>
</MDBCol>
</MDBRow>
<MDBBtn color="success" type="submit" onClick={() => { updateFormTeacher({ reponses}); this.showDisplayQuizz(); this.removeEmptyAnswer()}}>
Preview
</MDBBtn>
{this.state.isClicked === true ? (<DisplayQuizz evalStatus= {evalStatus} selectTest={selectTest} cancelForm={this.cancelForm} formData ={this.state} showDisplayQuizz={this.showDisplayQuizz}/>) : ""}
);
}
}
export default FormTeacher;
Quiz.jsx
const afficheInit = {
reponses: [],
}
class Quiz extends Component {
constructor(props) {
super(props);
this.state = {
test: afficheInit,
};
this.updateFormTeacher = this.updateFormTeacher.bind(this);
}
updateFormTeacher(consigne) {
this.setState({
test: consigne
}
}
Is it not working because updateFormTeacher doesn’t know about removeEmptyAnswer ? What did I miss ?
I feel a bit stupid to ask help for this kind of things but I am still a newbie and I think it’s better to feel stupid now and move forward instead of carry on to be stuck. So I hope some kind people will be able to help me.