0

How can I update the state using this.setState to set isPro to true?

this.state = {
userData: [{id: 1}, {username: 'John'}, {isPro: false}]
}
2
  • React state is SingleBinding. Must be re-set state by putting your new data Commented Nov 20, 2020 at 8:40
  • userData is not correct . must be object and not Array.look like userData: { id: 1 , username: 'John' , isPro: false} Commented Nov 20, 2020 at 8:47

2 Answers 2

2

Judging by how your data is structured, you may update it like this:

this.setState(prev => ({
  ...prev,
  userdata: [
    ...prev.userdata.filter(e => typeof e.isPro === 'undefined'), 
    { isPro: true }
  ]
}));

But if I were you, I probably going to make a function to update the state in the component class:

updateUserData(data) {
  this.setState(prev => {
    // make a copy of the previous state
    const copy = JSON.parse(JSON.stringify(prev));

    // assign values
    Object.entries(data).forEach(([k, v]) => {

      // find the entries that have the same key from the object that passed in
      const entries = copy.userdata.filter(entry => entry.hasOwnProperty(k));

      // If the entries exist, update them
      if(entries.length > 0) {
        entries.forEach(d => (d[k] = v));
      } 
      // otherwise, add a new entry
      else {
        copy.userdata.push({ [k]: v });
      }
    });

    return copy;
  });
}

And then update the data by calling:

this.updateUserData({ isPro: true, username: 'Bob' })

Then the state will be updated to

this.state = {
  userData: [{ id: 1 }, { username: 'Bob' }, { isPro: true }]
}
Sign up to request clarification or add additional context in comments.

1 Comment

TypeError: Cannot read property 'filter' of undefined
1

You can make a copy of the array, then find the index where the dictionary you want to modify is, and then modify it:

UPDATE (sorry about misprints, fast writing...)

    let userdatadummy = [...this.state.userData]
    const k = userdatadummy.findIndex((item)=>Object.keys(item).includes('isPro'))
    userdatadummy[k]['isPro']=true
    this.setState({
        userData: userdatadummy
    })

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.