sahar
sahar

Reputation: 33

How to get updated data in React

How to get updated data of react by calling the new data that will be received from another page by ajax?

How to replace new data to "Result" div.

class App extends React.Component {
  constructor(props){
    super(props);
      this.state = {
        data: [],
        }  
    $.ajax({
      url:"/test.bc",
      type:"get",
      success:(result)=>{
        this.setState({data: eval(result)});
      }
    })
    $(document).on('update_result',(event,startairline,classname,stops)=>{
      $.ajax({
        url:"/new.bc",
        type:"post",
        data:{
          startairline:startairline,
          stops:stops,
          classname:classname,
        },
        success:(result)=>{
          console.log(result)
          this.setState({hasBeenChanged: true,data:eval(result)})
        },
      })
    });
  }

  renderFlight(){
    return this.state.data.map((item)=>{ 
      return(<input type="hidden" value={item.total} name="total" /> )
    } )}

  render(){  
    return(<div>{this.renderFlight()}</div>  )
  }
}

ReactDOM.render(<App/>, document.getElementById('Result')); 

Upvotes: 1

Views: 343

Answers (1)

ene_salinas
ene_salinas

Reputation: 705

I prepare you an example, using componentDidMount and fetch:

Here working

    let { Table } = ReactBootstrap;

    class Example extends React.Component {
        constructor(props, context) {
        super(props, context);

        this.state = {
            products: []
        }
        }

        componentDidMount() {
        console.log('componentDidMount..')
        fetch('https://api.github.com/users/xiaotian/repos')
            .then(response => response.json())
            .then(output => {
            let products = []
            for (let i = 0; i < output.length; i++) {
                products.push({selected:false,name:output[i].name})
            }

            this.setState({products},() => console.log(this.state))

        })

        }

        render() {

            return(<Table striped bordered condensed hover>
                <thead>
                <tr>
                    <th>Selected</th>
                    <th>Name</th>
                </tr>
                </thead>
                <tbody>
                {this.state.products.map((item, i) => {
                    return (
                        <tr><td><input type="checkbox" checked={item.selected}/></td><td>{item.name}</td></tr>
                    ) 
                })}
                </tbody>
            </Table>)
        }
    }

    ReactDOM.render(
        <Example />, 
        document.getElementById('app')
    );

Upvotes: 1

Related Questions