Reputation: 35
I have three input fields in form and two buttons add questions and submit: In the first two field users can enter value one time in the third field users should be able to enter multiple values or multiple ques by clicking add questions and finally When the user submits the forms it should setState
<input type="text" name="intentName" />
<input type="text" name="Description" />
<input type="text" name="ques" />
state={
data:[
{"id":1,"intentName":"getPhoneNo","Description":"getting users phone no","ques":[{"q1":"how can i get users phone no"},{"q2":"give me phone number"}]},
]
}
i want to setState and add items to ques
for eg: i want to add {"id":2,"intentName":"getWifi","Description":"getting users phone no","ques":[{"q1":"how can i get users wifi password"},{"q2":"give me wifi password"}]}
Upvotes: 2
Views: 76
Reputation: 17664
pass a callback to this.setState
to get the previous data
and add the new object like :
data: [...prevState.data, obj]
Snippet :
/*
const state = {
data: [
{
id: 1,
intentName: "getPhoneNo",
Description: "getting users phone no",
ques: [{ q1: "how can i get users phone no" }, { q2: "give me phone number" }]
}
]
};
*/
this.setState(prevState => {
const obj = {
id: 2,
intentName: "getWifi",
Description: "getting users phone no",
ques: [{ q1: "how can i get users wifi password" }, { q2: "give me wifi password" }]
};
return {
data: [...prevState.data, obj]
};
});
Upvotes: 2