Event triggered on every select of a multiselect even though it is supposed to get fired only once

时间:2019-01-09 22:25:37

标签: react-native multi-select

I'm using this library https://github.com/toystars/react-native-multiple-select and followed the example in the readme / https://www.npmjs.com/package/react-native-multiple-select

Per the documentation, the onSelectedItemsChange is to be "Triggered when Submit button is clicked (for multi select) or item is clicked (for single select)".

However, in my code, the onSelectedItemsChange gets triggered every time I select an item.

I want to make an API call when I select all the items and click on the Submit button, so I don't want onSelectedItemsChange to be triggered on each item selection. Is there a way to accomplish that?

Here's the code I have

import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
import MultiSelect from './react-native-multiple-select';
import _ from 'lodash';
import Config from "react-native-config";

    const genre = [{
        id: 'b1',
        name: 'thriller',
    }, {
        id: 'b2',
        name: 'comedy',
    }, {
        id: 'b3',
        name: 'romance',
    }, {
        id: 'b4',
        name: 'biography',
    }, {
        id: 'b5',
        name: 'self help',
    }, {
        id: 'b6',
        name: 'cooking',
    }, {
        id: 'b7',
        name: 'coding',
    }
    ];

    const styles = StyleSheet.create({
        container: {
            backgroundColor: '#F5FCFF',
            padding: 10,
        },
        welcome: {
            fontSize: 20,
            textAlign: 'left',
            margin: 10,
        },
        instructions: {
            textAlign: 'center',
            color: '#333333',
            marginBottom: 5,
        },
    });


    class SelectBooks extends Component {
        constructor(props) {
            super(props);

            this.state = {
                genre: [],
                selectedItems: [],
                library: 'HS 1',
                result:  []
            }
        }
        makeRemoteRequest = _.debounce((library, genre) => {
            const host = Config.apiUrl;
            let apiCall = host + '/genre/pref/' + library + '?';
            if (genre !== null && genre !== undefined) {
                apiCall = apiCall + 'genre=' + genre.join();
            }
            if (apiCall.endsWith("?")) {
                apiCall = apiCall.substring(0, apiCall.length - 1);
            }

            const encodedUrl = encodeURI(apiCall);
            console.log('inside return statement in applyFilter: ' + encodedUrl);

            this.setState({ loading: true });
            fetch(encodedUrl)
                .then(res => res.json())
                .then(res => {
                    this.setState({
                        data: res.results,
                        error: res.error || null,
                        loading: false,
                    });
                    this.state.result = res.results;
                    console.log("response:" + JSON.stringify(res));
                })
                .catch(error => {
                    this.setState({ error, loading: false });
                });
        });

        onSelectedItemsChange = _.debounce((selectedItem) => {
            console.log('inside onSelectedItemsChange: ');
            this.setState({selectedItems: [...this.state.selectedItems, selectedItem]});
            console.log(this.state.selectedItems.join(','));
            this.state.result = this.makeRemoteRequest(this.state.library, this.state.selectedItems);
            console.log("filtered items: id:" + JSON.stringify(this.state.result));
            return this.state.result;
        },250);

        render() {
            return (
                <View style={styles.container}>
                    <MultiSelect
                        items={genre}
                        uniqueKey='id'
                        ref={(component) => {
                            this._multiSelect = component
                        }}
                        onSelectedItemsChange={this.onSelectedItemsChange}
                        selectedItems={this.state.selectedItems}
                        selectText='Select genre'
                        searchInputPlaceholderText='Search Items...'
                        tagRemoveIconColor='#CCC'
                        tagBorderColor='#CCC'
                        tagTextColor='#CCC'
                        selectedItemTextColor='#CCC'
                        selectedItemIconColor='#CCC'
                        itemTextColor='#000'
                        searchInputStyle={{color: '#CCC'}}
                        submitButtonColor='#444'
                        submitButtonText='Apply'
                    />
                </View>
            )
        }

        clearSelectedCategories = () => {
            this._multiSelect.removeAllItems();
        };

    }


export default SelectBooks;

This is the log statements I see: inside onSelectedItemsChange: romance .... (other log statements) inside onSelectedItemsChange: romance, coding

I want the onSelectedItemsChange to be triggered only after the Submit button is clicked. Can someone tell me what I'm doing incorrectly?

Note: The debounce does reduce the frequency and if I select items fast enough, I could get fewer API calls, but I would rather want the call to never get triggered until the Submit button is clicked (I believe that's what the documentation states as well).

Also, am super new to react-native, this is the first thing am trying to build.

0 个答案:

没有答案
相关问题