0

My objective is to change the value of an object and pass the modified object.

Here is the object:

{
  id: '12497wewrf5144',
  name: 'ABC',
  isVisible: 'false'
}

Here is the code:

class Demo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      demo: []
    }
  }

  componentDidMount() {
    axios
      .get('/api/random')
      .then(res => {
        this.setState({ demo: res.data})
      })
      .catch(error => {
        console.log(error)
      })
  }
  render() {
    return (
      <div>
{this.state.demo.map((user)=>
        <h1>{user.name}</h1>
        <input type="checkbox" value={user.value} />
)}
      </div>
    )
  }
}

export default Demo

I don't know what to write in onchange method for checkbox to only change the value within the object.

Note: value is string isVisible (we need to change value as boolean)

Can anyone help me in this query?

1
  • Does it make sense defining demo in the constructor as an empty object when it looks like the fetched data using Axios is an Array?, I think It should be defined as an empty array e.g: this.state = {demo: [] } Commented Aug 26, 2020 at 5:37

1 Answer 1

2

In order to change a certain key of an object you can use the following

this.setState({
  ...this.state,
  demo: {
    ...this.state.demo,
    isVisible: <NEW VALUE>
  }
})
Sign up to request clarification or add additional context in comments.

4 Comments

It is important to note that when using the spread operator you do not have to define each and every property - only the properties that you want to update.
It looks like demo is an array in the end when fetching is done
Yeah, looks like he's updating each user in the array.
Yes, if its in an array then he might need to update the value at that specific index, I just gave him an overview how the state can be updated

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.