Flatlist keep adding the list again when creating new object, with React Redux

Viewed 73

So I'm building an app in which I add an item in a Flatlist using React Redux to update the list everytime I navigate to the page, the problem is that the Flatlist doesn't behave the way I thought it would, when I press the button with the .submitItem and I navigate to the next screen, the Flatlist instead of updating the array and showing only the items I newly added, it adds the same list again showing at the same time the previous list and the current list, I find it hard to explain so I hope it's more clear with the code below:

ADD ITEM SCREEN

class addItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: id,
      name: name,
      lastName: lastName,
      list: this.props.list,
        };
  }

  submitExercise(){                              
    let list = this.state.list;
    list.push({
        id: id,
        name: name,
        lastName: lastName,
    });
    this.props.updateList(list);
    this.props.navigation.navigate("ListItem");
  }

render() {
    return (

      <Button onPress={this.submitExercise()}>Submit</Button>
   )}}

function mapStateToProps(store){
  return{
      list: store.userState.list
  };
}

const mapDispatchToProps = { updateList };

export default connect(mapStateToProps, mapDispatchToProps)( addItem );

ITEM LIST SCREEEN

class ListItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],

    };  }

  static getDerivedStateFromProps(props, state) {
    if (props?.list) {
      return {
        list: [...state.list, ...props.list],
      };
    }
    return null;
  }

render() {
    return (

       <FlatList
            data={this.state.list}
            renderItem={({ item }) => (
            <View>
                <Text>{item.name}</Text>
                <Text>{item.lastName}</Text>
             </View>
            )}
            keyExtractor={(item, index) => item.id}
          />

)}}

function mapStateToProps(store){
  return{
      list: store.userState.list
  };
}
export default connect(mapStateToProps)(ListItem);

FUNCTION updateList

export const updateList = (list) => {
  return { type: ADD_ITEM, payload: list}

}
1 Answers

Please change

  <Button onPress={this.submitExercise()}>Submit</Button>

to

  <Button onPress={this.submitExercise}>Submit</Button>

because its executing your submitExcercise function on the mount of the Component other things seems alright in your Code.

Related