-2

I change the name and age dynamiclly by creating two handlers. When I input an age it changes dynamicly. There is no problem here. But the name goes default as well. Because I defined it as a hard-coded value in 'ageChangeHandler'.But i want the name to stay like I did in the 'nameChangeHandler'. Is there something like 'currentValue' or 'lastValue' in Javascript/ES6? I hope I explained it properly. Thanks in advance.

I couldnt find any options like currentvalue etc.

    nameChangeHandler = (event) =>{ 
this.setState({
  persons: [
    {name: "Max" , age: 28},
    {name: event.target.value, age: 29},
    {name:"Arthur", age:34}
  ]
})

}

ageChangeHandler = (event) =>{
this.setState({
  persons:[
    {name: "Max" , age: 28},
    {name: "Tom", age: 29},
    {name:"Arthur", age:event.target.value}
  ]
})}

Lines I call handlers:

<Person 
      name={this.state.persons[0].name} 
      age={this.state.persons[0].age}/>
    <Person 
      name={this.state.persons[1].name} 
      age={this.state.persons[1].age}
      click={this.switchNameHandler.bind(this, "Way 2")}
      Namechanged={this.nameChangeHandler}>My hobbies: coding</Person>
    <Person 
      name={this.state.persons[2].name} 
      age={this.state.persons[2].age}
      Agechanged={this.ageChangeHandler}/>

3 Answers3

-1

If you pass a function, instead of an object to setState, you get this signature:

this.setState((prevState, props) => {
 // do something with prevState
 return { ...prevState }
});

allowing you to use the previous state to create the new one.

so In your case:

this.setState(prevState => {
  return {
      ...prevState,
      persons: prevState.persons.map(person => {
        if (person.name === "Arthur") return { ...person, age: e.target.value }
        return person
     })
  }
})

or something like that.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Christopher Reid
  • 4,318
  • 3
  • 35
  • 74
  • Two states may be previous states. I can change before age than name. What to do then? – Yusuf Mert Çakmak Sep 10 '19 at 18:29
  • and I don't know how to make both states as 'prevState'. – Yusuf Mert Çakmak Sep 10 '19 at 18:29
  • @YusufMertÇakmak see my edit. Basically you use the spread operate (...) to fill the new state with the old one, and then make modifications accordingly. My example takes the previous persons list and prints it out but uses a map to change the value on the field you want to target. – Christopher Reid Sep 10 '19 at 18:31
  • 1
    @YusufMertÇakmak whenever you call `setState`, there will only be ONE `prevState`. You could do both modifications at once, or one after the other depending on what makes sense. – Christopher Reid Sep 10 '19 at 18:35
  • `.map` already returns a new array, there's no need to spread the result into an array. – Emile Bergeron Sep 10 '19 at 18:35
  • I didn't noticed at first, but `person.age = e.target.value` is mutating the state directly. Return a new object instead. `if (condition) return { ...person, age: e.target.value };` – Emile Bergeron Sep 10 '19 at 18:41
-1

You can use an index to dynamically select a user to edit and then just update its attributes:

nameChangeHandler = (event) => {
   const { index } = this.state;
   this.setState({
     persons: this.state.persons.map((item, j) => {
        if (j === index) {
           return {
              ...item,
              name: event.target.value,
           };
        } else {
           return item;
        }
     }),
   });
}

You could also create a universal function to update any number of parameters:

<input
    type="text"
    // Here we send a value, n index (can be from state) and the parameter to update
    onChange={(e) => { this.changeHandler(e.target.value, 0, 'name') }}
/>

changeHandler = (value, index, attr) => {
    // index is the object in the array that we want to update 
    // attr is the key
   this.setState({
     persons: this.state.persons.map((item, j) => {
        if (j === index) {
           return {
              ...item,
              [attr]: value,
           };
        } else {
           return item;
        }
     }),
   });
}
joseluismurillorios
  • 1,005
  • 6
  • 11
-1

Declared an ID for all of persons :

state = {
persons: [
  {id:"25343", name:"Max", age: 28},
  {id:"24323ad ", name: "Tom", age: 29},
  {id:"asdavd231", name:"Arthur", age:34}
],

Updated them with their ID's :

  ageChangeHandler = (event,id) =>{
const personIndex = this.state.persons.findIndex(p=>{
  return p.id === id;
})
const person = {
  ...this.state.persons[personIndex]
}
person.age = event.target.value;
const persons = [...this.state.persons]
persons[personIndex] = person;
this.setState({persons:persons})}

Rendered them in a map:

<div>
      {this.state.persons.map((person,index)=>{
        return <Person 
        click={() => this.deletePersonHandler(index)} //map'ten gelen index deletePersonHandler'a pareametre olarak gönderiliyor
        name={person.name} //map'in 1.parametresi. (persons'u işaret ediyor)
        age={person.age}
        key={person.id}
        nameChanged={(event)=>this.nameChangeHandler(event,person.id)}
        ageChanged={(event)=>this.ageChangeHandler(event,person.id)}/>
      })}

    </div>