react-nativemulti-selectpass-data

React Native Multiselect


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!!


Solution

  • 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.