Pouya Ataei
Pouya Ataei

Reputation: 2169

Updating the state via eventHandler

The piece of code below is a two-way binding in ReactJS, whereas one types, the text and input values update simultaneously.

Here's the Component loop:

if (this.state.personState){

  persons = (

    <div> 

      {this.state.person.map( (person, index) =>{
          return 
             <Person 
                click = {()=>this.deletePerson(index)}
                name = {person.name} 
                age = {person.age} 
                key = {person.id} 
                changed = { (event)=>this.changeNameHandler(event, person.id)} >
             </Person>
      })}

    </div>

)

The function that handles the event

changeNameHandler = (event, id) => {

   const personIndex = this.state.person.findIndex(person => person === id)

   // making a copy and not manipulating the original reference
   const personcpy = { ...this.state.person[personIndex] }

   // assign the value of the event target
   personcpy.name = event.target.value;

   // making a copy of the state to update the dom
   const persons = [...this.state.person]

   // updating...
   persons[personIndex] = personcpy

   // state update
   this.setState({ persons : persons })

}

The Javascript Object itself

state = {
  person : [
    {id:'12121', name:"Jimmy", age:12},
    {id:'121s', name:"Jack", age:15},
    {id:'23232a', name:"pouya", age:27}
  ]
} 

The component codes

const Person = (props) => {
    return (
        <div className="Person" >
        <p  onClick={props.click}>I'm {props.name} and I'm {props.age} years old</p>
        <input  onChange={props.changed} value={props.name} />
        <h1 >{props.name}</h1>
        </div>
    )
}

I'm aware that findIndex() returns the index of the first element in the array that satisfies the given test.

And I'm testing if the index of the event on change is the same as the object one!

However, this does not work, and when I try to type it just freezes

I've checked Chrom's developer tools and tried to debug there, it seems like there is a reference error! but I don't understand! how could that be?

enter image description here

Please help me see from different point of view.

Upvotes: 4

Views: 87

Answers (2)

Sv3n
Sv3n

Reputation: 347

Did you get an valid personIndex? Probably you should write findIndex(person => person.id === id)

Upvotes: 1

喝茶的螃蟹
喝茶的螃蟹

Reputation: 144

It seems that reference of this.state.person not changed, component will not re-render. try this below in changeNameHandler:

// ...ellipsis code ...

this.setState({ person: [...persons] })

And in your state, person is declared, but update persons in setState, is that miss type?

Upvotes: 0

Related Questions