anshul sinha
anshul sinha

Reputation: 31

Component losing the previous state

I'm calling the child component ExpandableListItem in a parent component parentscreen.js.whenever I clicked on any item of expandable list item it calls the getAnswer method and set the state questionlistarray.My concern is whenever clicked on any item of expandable list item in child component it always override the previous state of questionlistarray ,but I want previous state shouldn't override and should add to new state.

parentscreen.js

<View style={{ height: this.state.layout_Height, overflow: 'hidden' }}> {
  this.props.item.sub_Category.map((item, key) => (
  <View style={styles.sub_Category_Text}>
    <Text style={{ fontWeight: 'bold' }}> {item.sub_name} </Text>
    {
    item.name.map((item1, key) => (
    <View>
      <Text style={{ marginTop: 10 }}> {item1.question} </Text>
      <ExpandableListItem                                            
        quesId={item1.question_id}
        assignedToList={ this.props.assignedToList}
        setAnswer={this.getAnswer} />
      {/* {this.renderQuestions(item1.question_id, this.props.assignedToList)} */} </View>
    ))
    } </View>
  ))
  } </View>
  getAnswer = (obj) => {
        var array = this.state.questionsListArray;
        // AsyncStorage.getItem('qArray').then((value) => {
        //    if (value != null) {
        //      //this.setState({ questionsListArray: value })
        //      // console.log(value)
        //      array = value;
        //    } else {
        //         array = this.state.questionsListArray
        //   }
        // })

        for (var key in obj) {
            var c = array.filter((item) => item.question_id != key)
            c.push(obj[key]);
        }

        c.map((item, key) => (
            console.log("array is " + " " + item.question_id + " " + item.Answer + " " + item.comment + " " + item.assignedTo + " ")
        ))

        // AsyncStorage.setItem('qArray',JSON.stringify(c));
        this.setState({
            questionsListArray: c,
        })
    }

Upvotes: 0

Views: 943

Answers (2)

Lavanya Ravi
Lavanya Ravi

Reputation: 56

getAnswer = (obj) => {
    var array = this.state.questionsListArray;

    for (var key in obj) {
        array.push(obj[key]);
    }

    this.setState({
        questionsListArray: array
    })   
}

You seem to be filtering out the corresponding question and then push another object into the array, overriding it. I've just removed the filter. Now, it should add to the state and not override anything.

Upvotes: 0

user10104341
user10104341

Reputation:

You probably need something like the below:

this.setState(prevState => ({
      ...prevState,
      questionsListArray: c
    }));

If you are wondering where prevState is coming from, React is optionally providing it as. Since setState, re-renders the Component, it will not keep the previousState. You need to pass it, explicitly. Hope I helped!

Upvotes: 1

Related Questions