0
votes

I am new to React Native

I am trying to create a multiselect view where user can select and deselect the items and then the selected items should pass back to the previous container and when user comes back to the next view the selected items should be checked.

I am trying to implement but getting the issue it is not updating data accurately. It shows only 1 selected item when I came back again to the screen.

Can anyone tell me the best way to do that or if there is any tutorial.

Should I do it with Redux or using react native?

Any help would be appreciated!!

Thanks!!

1
Can you share your current implementation and how you're managing the state of the selected data? It's hard to give advice without a bit more detail. - azundo
Sure let me do that. - User511
@azundo Please check - User511
@azundo And I am passing the data from previous view using this . - User511
popToNextView = () => { const { navigation } = this.props; navigation.navigate('multiselect',{returnData: this.returnData.bind(this),data: this.state.brandsArr}); }; - User511

1 Answers

1
votes

I believe the issue you describe is due to the following:

In componentDidMount you are calling updateItemWithSelected in a loop. This updateItemWithSelected call is both overwriting the checked attributes for all of the arrayHolder values on each call and also not using the updater function version of setState, so the later call of the loop may overwrite the earlier calls since setState is async and batched. If you are not using updateItemWithSelected elsewhere you should simplify componentDidMount to:

  componentDidMount() {
    const selectedTitles = {};
    const { state } = this.props.navigation
    const params = state.params || {}; 
    if (params.data.length){
      params.data.forEach((element) => {
        // create a map of selected titles
        selectedTitles[element.title] = true;
      })
    }
    const arrayHolder = this.array.map(item => {
      // map over `this.array` and set `checked` if title is in `selectedTitles`
      return {...item, checked: !!selectedTitles[item.title]};
    });
    this.setState({ arrayHolder });
  }

and delete updateItemWithSelected.