2

I need to filter list of question by category so I decided to add category_id in empty table categories on checkbox change but the table stay empty?

// Définition of state

constructor(props) {
    super(props);
    this.handleCategoryChange.bind(this)
    this.state = {
        filters: []
    }
}

// Checkbox Categories change

handleCategoryChange (category, e) {
    if (e.target.checked) {
        this.setState((state) => ({
            filters: [[...state.filters], ...[category.id]]
        }));
        console.log(this.state.filters) // empty
    }
}

// Checkbox input

render() {
    return (

        <div className="form-check mb-2">
            <input className="form-check-input" type="checkbox" id={'category-'  + this.props.category.id} onChange={(e) => this.handleCategoryChange(this.props.category, e)}/>
            <label className="form-check-label" htmlFor="category">
                { this.props.category.name }
            </label>
        </div>
    )
}

2 Answers 2

1

First of all... setState() is asynchronous operation so console.log(this.state.filters) may or may not be empty. Try code below. You should debug it to work properly after check/uncheck category.

 handleCategoryChange (category, e) {

        if (e.target.checked) {
             const filters = [...this.state.filters,
                   category.id
             ]
            this.setState({
                filters: filters
            });
            console.log(this.state.filters) // empty
        } else {
               //....
         }
    }
Sign up to request clarification or add additional context in comments.

Comments

0
handleCategoryChange (category, e) {
    if (e.target.checked) {
        this.setState((state) => ({
            filters: [...state.filters, ...category.id]
        }), (newState) => console.log(newState.filters));
    } else {
        const newFilters = [...state.filters];
        newFilters.splice(category.id, 1);
        this.setState((state) => {
            const newFilters = [...state.filters];
            newFilters.splice(category.id, 1);
            return {
                filters: [...state.filters, ...category.id]
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.