javascript - json data as react state is not updated -
i learning develop app using reactjs in frontend.
i should response server json. interested in particular array object in json. need display updated data in browser. should updated realtime in browser. : understanding resultant json should state property in react , whenever updated in server re-rendered in webpage. tried following:
class app extends component { constructor(props){ super(props); this.state = { result: [], } componentdidmount(){ var =this; axios.get('url').then(function(response){ for(i=1;i<response.data.result.length;i++) { var array = that.state.result.slice(); array.push(response.data.result[i]) that.setstate({ result: array }) }); } } render(){ <div> <h1> result is: {this.state.result}</h1> </div> this makes request once server , displays data available @ moment.
when json updated in server due other actions after initial get, real time data not updated in browser. isn't purpose of axios.get call? continuously fetch real time data? sorry new frontend.
is correct way: data fetched server(array part of json) directly assign in state using loop? or there simpler/correct way assign json directly state in component?
why can't directly use this.setstate in componentdidmount() method? why should assign "var that"? if use directly it's throwing error setstate property cannot read null value , though assigned initial value in constructor?
thanks.
Comments
Post a Comment