1

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')); 
c-chavez
  • 7,237
  • 5
  • 35
  • 49
sahar
  • 13
  • 5
  • a couple of questions, why are you using jquery? why ajax and not fetch or axios? – c-chavez Oct 31 '18 at 12:02
  • Also, you cannot call setState in the constructor, have a proper read [at the official docs](https://reactjs.org/docs/react-component.html#setstate). Use `componentDidMount` for this. – c-chavez Oct 31 '18 at 12:07
  • Im new in react native, Could you please edit my code? – sahar Oct 31 '18 at 12:23
  • don't worry if you are new. Have you already read the link I added? – c-chavez Oct 31 '18 at 12:28
  • Yes,but actually i am confused about componentDidMount. I try to use componentDidMount() { axios.post(`new.bc`,{startairline,classname,stops}) .then(res => { const data = res.data; this.setState({ data }); }) } instead of $.ajax({ url:"/new.bc", type:"post",.........}) but it doesnot work! – sahar Oct 31 '18 at 12:43
  • that is the correct way, why didn't it work? did you get an error message? axios is the best and easiest IMHO. Have a look [here](https://stackoverflow.com/a/50326744/1042409) – c-chavez Oct 31 '18 at 13:01
  • Error message :SyntaxError and it is because of componentDidMount(). I try the link you added, but there is the same error about this line : let response = await axios(options); – sahar Oct 31 '18 at 13:18
  • please edit your question and add the code with these changes so I can see what is going on. If you use async/await you have to make the function async with `async componentDidMount() {` – c-chavez Oct 31 '18 at 13:45
  • There is a div called Result in my page.By default data of json.bc(json.bc contains json) would be shown in this div , but after checking a checkbox the data of newjson.bc(json) must be represent in Result div and the previous data must be remove and new data must be shown in Result div. – sahar Oct 31 '18 at 14:21
  • – sahar Oct 31 '18 at 14:22
  • $.ajax({ url:"/json.bc?from=[##cms.query.from##]&to=[##cms.query.to##]&fdate=[##cms.query.fdate##]&tdate=[##cms.query.tdate##]&adult=[##cms.query.adult##]&child=[##cms.query.child##]&select-age=[##cms.query.select-age##]&share=[##cms.query.share##]&userid=[##db.userid.userid##]", type:"get", success:(result)=>{ this.setState({data: eval(result)}); } }) – sahar Oct 31 '18 at 14:23
  • $(document).on('update_result',(event,startairline,classname,stops)=>{ componentDidMount() { axios.post(`newjson.bc`,{startairline,classname,stops,from :"[##cms.query.from##]",to:"[##cms.query.to##]",fdate:"[##cms.query.fdate##]",tdate:"[##cms.query.tdate##]",share:"[##cms.query.share##]",userid:"[##db.userid.userid##]",username:"[##db.UserName.answer##]",adult: "[##cms.query.adult##]",childcountandage: "[##cms.query.child##][##cms.query.select-age##]",}) .then(res => { console.log(res); console.log(res.data); const data = res.data; – sahar Oct 31 '18 at 14:24
  • this.setState({data}); }) } }); } – sahar Oct 31 '18 at 14:24
  • renderFlight(){ return this.state.data.map((item)=>{ return(
    {item.id}
    ) } ) } render(){ return(
    {this.renderFlight()}
    ) } } ReactDOM.render(, document.getElementById('Result'));
    – sahar Oct 31 '18 at 14:25

1 Answers1

1

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')
    );
ene_salinas
  • 705
  • 4
  • 11