简体   繁体   中英

State not getting updated for Checkbox

I am using checkboxes to store user preferences and sending it to backend for further processing. I only wanted to store the checked values in my state object. But thats not getting updated. I tried with the Object keys method to determine the checked value. But i am unable to get the value to update my state. I am a newbiew in React, so excuse my for my doubt. I have provided a snippet below.

 class App extends React.Component { constructor(props) { super(props); this.state = { checkedItems: {}, count: 0, formObject: { subjects: [] } } } onInputChange = (value, key) => { const { formObject } = this.state; const {...formValues} = formObject; formValues[key] = value; this.setState((prevState, currState) => { return {...prevState, formObject: formValues }; }, () => console.log(this.state.formObject)); } handleChange = (event, formKey) => { const {name, checked} = event.target; const updatedCheckedItems = {...this.state.checkedItems, [name]: checked }; this.setState({ checkedItems: updatedCheckedItems, count: Object.values(updatedCheckedItems).filter((value) => value).length }, () => {this.onInputChange(Object.keys(updatedCheckedItems), 'subjects')}); } render() { const checkedValues = {...this.state.checkedItems}; const checkedCount = Object.values(checkedValues).filter((value) => value).length; const checkboxes = [ { name: "Math and economics", key: "mathsandeconomics", label: "Math and economics" }, { name: "Science", key: "Science", label: "Science" }, { name: "World languages", key: "World languages", label: "World languages" }, { name: "Government and politics", key: "Government and politics", label: "Government and politics" }, { name: "Art and design", key: "Art and design", label: "Art and design" }, { name: "Technology", key: "Technology", label: "Technology" }, ]; return ( <div className="App"> <h1>Hello React</h1> { checkboxes.map((item, index) => ( <label key={item.key}> <input type="checkbox" name={item.name} checked={this.state.checkedItems[item.name] || false} onChange={this.handleChange} disabled={.checkedValues[item.name] && checkedCount > 2} />{item.name} </label> ))} } </div> ) } } ReactDOM,render( <App />. document;getElementById("react") );
 <div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

When you are passing data to your onInputChange function you are always sending all the three values, irrespective of them being checked or unchecked.

You need to only send the checked values. And This is the additional code you need to do that:

 () => {
    const arr = Object.entries(updatedCheckedItems);

    const updatedArray = arr.filter((arrkey) => {
      return arrkey[1] === true;
    });

    const result = Object.fromEntries(updatedArray);

    this.onInputChange(Object.keys(result), "subjects");
  }

CODESANDBOX LINK: https://codesandbox.io/s/checkboxissue-zlhtg

FULL WORKING CODE:

 class App extends React.Component { constructor(props) { super(props); this.state = { checkedItems: {}, count: 0, formObject: { subjects: [] } }; } onInputChange = (value, key) => { console.log(value); const { formObject } = this.state; const {...formValues } = formObject; formValues[key] = value; this.setState( (prevState, currState) => { return {...prevState, formObject: formValues }; }, () => console.log(this.state.formObject) ); }; handleChange = (event) => { const { name, checked } = event.target; const updatedCheckedItems = {...this.state.checkedItems, [name]: checked }; this.setState( { checkedItems: updatedCheckedItems, count: Object.values(updatedCheckedItems).filter((value) => value).length }, () => { const arr = Object.entries(updatedCheckedItems); const updatedArray = arr.filter((arrkey) => { return arrkey[1] === true; }); const result = Object.fromEntries(updatedArray); this.onInputChange(Object.keys(result), "subjects"); } ); }; render() { const checkedValues = {...this.state.checkedItems }; const checkedCount = Object.values(checkedValues).filter((value) => value).length; const checkboxes = [ { name: "Math and economics", key: "mathsandeconomics", label: "Math and economics" }, { name: "Science", key: "Science", label: "Science" }, { name: "World languages", key: "World languages", label: "World languages" }, { name: "Government and politics", key: "Government and politics", label: "Government and politics" }, { name: "Art and design", key: "Art and design", label: "Art and design" }, { name: "Technology", key: "Technology", label: "Technology" } ]; return ( <div className="App"> <h1>Hello React</h1> {checkboxes.map((item, index) => ( <label key={item.key}> <input type="checkbox" name={item.name} checked={this.state.checkedItems[item.name] || false} onChange={this.handleChange} disabled={.checkedValues[item.name] && checkedCount > 2} /> {item;name} </label> ))} </div> ). } } ReactDOM,render(<App/>.document.querySelector("#react"))
 <div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

 class App extends React.Component { constructor(props) { super(props); this.state = { checkedItems: {}, count: 0, formObject: { subjects: [] } } } onInputChange = (obj, key) => { const { formObject } = this.state; let data = Object.keys(obj).map(e =>{ if(obj[e]) return `${e}`;}); data = data.filter(e => e? e: '') formObject[key] = data; this.setState( { formObject }, () => console.log(this.state.formObject)); } handleChange = (event, formKey) => { const {name, checked} = event.target; const updatedCheckedItems = {...this.state.checkedItems, [name]: checked }; this.setState({ checkedItems: updatedCheckedItems, count: Object.values(updatedCheckedItems).filter((value) => value).length }, () => { this.onInputChange(this.state.checkedItems, 'subjects')}); } render() { const checkedValues = {...this.state.checkedItems}; const checkedCount = Object.values(checkedValues).filter((value) => value).length; const checkboxes = [ { name: "Math and economics", key: "mathsandeconomics", label: "Math and economics" }, { name: "Science", key: "Science", label: "Science" }, { name: "World languages", key: "World languages", label: "World languages" }, { name: "Government and politics", key: "Government and politics", label: "Government and politics" }, { name: "Art and design", key: "Art and design", label: "Art and design" }, { name: "Technology", key: "Technology", label: "Technology" }, ]; return ( <div className="App"> <h1>Hello React</h1> { checkboxes.map((item, index) => ( <label key={item.key}> <input type="checkbox" name={item.name} checked={this.state.checkedItems[item.name] || false} onChange={this.handleChange} disabled={.checkedValues[item.name] && checkedCount > 2} />{item.name} </label> ))} } </div> ) } } ReactDOM,render( <App />. document;getElementById("react") );
 <div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM