D
D
Denis Voronin2018-07-18 17:10:24
React
Denis Voronin, 2018-07-18 17:10:24

How to collect data into an object on input click?

I output the following input:

render () {

    const { id, name, value, adress } = this.props

 return (                             
      <p className="adressPoint"> 
        <input type="radio" className="radio" id={ id } name={ name } value={ value } onChange = { e => this.handleChangeOffice ( e ) } />
        <label htmlFor = { id } > { adress } </label>
      </p>                                    </b>             
    )
  }
}

On click, you need to collect an object that will contain pairs of id and value, that is,
{ id: value ,
id2: value2 }.
Initially, the idea was to put objects in state, but since it works asynchronously, the data is overwritten, that is, at the time the current state variable is received, there is already a new state there. Handler code:
handleChangeOffice (e) {

    const { getIdAndOffice } = this.props;

    const id = e.target.name;
    console.log(id);

    const idAndOffice = this.state.radioValue
    console.log(idAndOffice);
  
    idAndOffice[id]= e.target.value;
    console.log(idAndOffice);

    this.setState({
      radioValue: idAndOffice
    });
    console.log(this.state.radioValue)

    this.props.getIdAndOffice(this.state.radioValue)
    console.log(this.props.getIdAndOffice(this.state.radioValue))

  }

I think you need to declare a variable outside the handler function where the data will fall, but there is a problem with the scope. I tried to pass a variable through props from the parent component, the result is the same as when working with the state.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
string15, 2018-07-18
@string15

It won't work , maybe you need to{ { id: value }, { id2: value2 } }
[ { id: value }, { id2: value2 } ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question