lundi 28 octobre 2019

React input checkbox not updating state indirectly

Unfortunately I didn't understand logic of input checkbox in render. Here is the problem:

1) I have input type checkbox with onChange and checked attributes on it;
2) Also I have button handleSearch which gets API information from backend after clicking the button;
3) If I will click on checkbox it will also receive information from API(from same API as in second step with same parameters).

Problem is: If I will click checkbox it will send falsy parameter of checkbox because, as I understand, it is working vice-versa for some reason. But, if I will try to first click button it will work OK.

So I need to send truthy parameter on handling checbox.

input in render():

    <input
        type="checkbox"
        className="custom-control-input"
        name="grouping"
        id="updateprice"
        checked={grouping}
        onChange={this.onGroupingChange}
    />      

checkbox handler():

      onGroupingChange = (e) => {
         const {grouping} = this.state;
        this.setState({ grouping: e.target.checked});
             this.getSales(grouping);
    };

OnClick handler():

      handleSearch = () => {
        const { grouping  } = this.state;
        this.setState({ isLoading: true });
        this.getSales(grouping);
    };

getSales()

getSales = (grouping) => {
        let notattr;
        if (grouping===false){
            notattr=1
        }
        else notattr = 0
        this.setState({isLoading: true})
        Axios.get('/api/report/sales', {
            params: { notattr }

        })
        .then(res => res.data)
            .then((sales) => {
                this.setState({
                    sales,
                    isLoading: false,
                    handleGrouping: true,
                    activePage: 1,
                    currentRange: {
                        first: (this.state.itemsPerPage) - this.state.itemsPerPage,
                        last: (this.state.itemsPerPage) - 1
                    },
                    orderBy: ''
                })
            })
            .catch((err) => {
                this.setState({isLoading: false})
                console.log(err)
            })
    };

basic problem scenario 1:
1) I'm opening page;
- checkbox in screen true;
2) I'm clicking search button;
- API sends noattr:0 because grouping:true;
3) Now, I want to click checkbox;
- API still sends noattr:0 because grouping:true(but I was expecting grouping:false value)
4) If I will handle checkbox later it will work vice-versa. But if I will handle search button, it will send OK information.
Obviously there is small mistake somewhere, but I tried a lot of different combinations and it seems that didn't find right one.




Aucun commentaire:

Enregistrer un commentaire