Reputation: 143
Hi guys i need help how to make the editchange will not go through all the input and make changes to it.
When i typed an input inside one of the textbox it repeats to other inputs. Im new to react so i having trouble dealing with this.
the map is on loop, for example it displays three from api and 3 inputs will appear.
See the picture, hope you can help me.
handleSubmitReply(event, discussionid, classid){
event.preventDefault();
let userid = sessionStorage.getItem('userid');
const {
userAccountId,
reply
} = this.state;
const postData = {
userAccountId:userid,
reply
};
let sessionToken = sessionStorage.getItem('session');
let sessToken = sessionToken.replace(/\"/g, "");
fetch('http://tfismartasp-001-site10.btempurl.com/api/Class/'+ classid +'/discussion/'+discussionid+'/response', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer' + " " + sessToken
},
body: JSON.stringify(postData),
})
.then(response => {
if(response.status === 400){
return response.json();
}else{
this.addNotification('success', 'Success', 'All Data is Saved', 'top-right')
this.componentDidMount();
return response.json();
}
})
.then(responseData => {
console.log(responseData);
return responseData;
})
.catch(err => {
console.log("fetch error" + err);
});
}
this.handleChange = this.handleChange.bind(this);
handleChange(event) {
event.preventDefault();
console.log(event.target.name)
console.log(event.target.value)
this.setState({
[event.target.name]: event.target.value
});
};
{discussionData.map(dd => (
<input type="text" class="form-control bg-light" placeholder="Reply" name={dd.discussion.instructions} value={this.state[dd.discussion.instructions]} onChange={this.handleChange} />
))}
here is the updated code, what will i do to the postData "reply" when i submit it. it requires to fill all the fields.
How to serialize it to be posted in my API
Upvotes: 0
Views: 103
Reputation: 728
Try Something like that
handleChange(event, i) {
event.preventDefault();
console.log(event.target.name)
console.log(event.target.value)
this.setState({
[`${event.target.name}{index}`]: event.target.value
});
};
{items.map((item, index)=> (
<input type="text" class="form-control bg-light" placeholder="Reply" name=`name${index}` value=
{this.state.reply} onChange={e => this.handleChange(e, index)} />
))}
And create initial state as an array. May be this will help you.
Thanks
Upvotes: 0
Reputation: 2833
event.target.name
will always be "reply"
as every one of your inputs has name="reply"
.
Giving every input a unique name should fix your problem.
Upvotes: 1