Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Direct modification of 'AddNinja' component state #2

Open
vedhant opened this issue Sep 9, 2018 · 1 comment
Open

Direct modification of 'AddNinja' component state #2

vedhant opened this issue Sep 9, 2018 · 1 comment

Comments

@vedhant
Copy link

vedhant commented Sep 9, 2018

over here :

 handleSubmit = e => {
  e.preventDefault();
  this.props.addNinja(this.state);
 }

while passing this.state in addNinja() function, we are actually passing the state of 'AddNinja' component directly as reference to the function. So this 'AddNinja' state is directly being modified :

 addNinja = (ninja) => {
    ninja.id = Math.random();     // state modified directly here
    this.setState({
      ninjas: [...this.state.ninjas, ninja]
    });
  }

here an id is added directly to 'AddNinja' state which should not be done and hence gives me error when i give submit on same data more than once.

@michaelortega
Copy link

michaelortega commented Oct 5, 2018

@vedhant I have found a solution to this Issue.

First, modify the state inside the AddNinja Component and add a field "id"

class AddNinja extends Component {
    state = {
        name: null,
        age: null,
        belt: null,
        id: null //ADD THIS
    };

...

Second modify the handleSubmit method as follows

// Still inside AddNinja.js
handleSubmit = e => {
        e.preventDefault();
        this.props.addNinja({
            ...this.state,
            id: Math.random()
        });
       // this.props.addNinja(this.state); REMOVE THIS
    };

Lastly, remove the Math.Random() from the main App.js Compoent

class App extends Component {
...
 
  addNinja = (ninja) => {
    //ninja.id = Math.random(); REMOVE THIS
    let ninjas = [...this.state.ninjas, ninja];
    this.setState({
      ninjas: ninjas
    });
  }
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants