0

I have a series of data in which there is a form in every item. I try to use index in onSubmit event and when I check index of for loop in console, it shows the correct index, but when I check index of

handleSubmitR=(e, DetailsRoom, index)=>{console.log(index)} 

it is different from the index in for loop.

For example, if I have 3 forms in one item the result of the index in for loop is

'01','02' ,'03'

but in onsubmit event the result of index is **

'03','03','03'

Any suggestions?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      resultEdit: {},
    };

    $.ajax({
      url:"/json.bc",
      type:"post",
      success: (result) => {
        this.setState({data: eval(result)});
      }
    })
  }

  renderHotel(){
    return this.state.data.sort((a, b) => a.total - b.total).map((item,i)=>{
      return (
        <div class="items">
          {this.renderDetailsRoom(item,i)}
        </div>
      )
    })
  }

  renderDetailsRoom(DetailsRoom,i){
    let lenfamilies = DetailsRoom.families.length 
    var indents =[];
    for(var j = 0 ;j <lenfamilies;j++){
      var numF = i;
      var numS = j;
      var stingF = numF.toString();
      var stingS = numS.toString();
      var  index= stingF+stingS
      **////
       <!-----e.g. For two forms  the result of consol.log(index) = '00' and '01'----->
       /////**

      indents.push(<form method="post" key={index}  action={this.renderAction(DetailsRoom)}  onSubmit={e => this.handleSubmitR(e, DetailsRoom, index)}><div  class="Result">{this.state.resultEdit[index]}</div></form>)
    }
    return(
      indents
    )
  }

  handleSubmitR=(e, DetailsRoom, index)=>{
        ////
       <!-----but the result of consol.log(index) in this part for both form are '01'----->
       /////
    console.log(index)
    e.preventDefault();
    return  this.setState( prevState => ({
      resultEdit: { ...prevState.resultEdit, [index]:'submitted'},
    })) }
  render() {
    return (
     <div>{this.renderHotel()}</div>);
  }
}

ReactDOM.render(<App/>, document.getElementById('Result'));
c-chavez
  • 7,237
  • 5
  • 35
  • 49
bita
  • 335
  • 2
  • 9
  • 22
  • why use jquery? if you are going to do a fetch of data don't do it in the constructor, but rather do it in componentDidMount, have a read [here](https://reactjs.org/docs/react-component.html#componentdidmount) and maybe consider using [axios](https://github.com/axios/axios), read [this answer to see if it helps](https://stackoverflow.com/a/50326744/1042409) – c-chavez Nov 22 '18 at 08:24
  • Thanks but i think there is no different in number of index! My main problem is about 'index'. – bita Nov 22 '18 at 08:27
  • correct. but first follow good guidelines and you will for sure avoid some other side effects. Also, that's why this is a comment and not an answer ;) – c-chavez Nov 22 '18 at 08:44

0 Answers0