score:3

Accepted answer

the problem is that the data is not yet available when react renders the component. in practice, your code should guard against this, either at the component or above:

render() {
  if(!this.state.items) return null; // or loading indicator, data has not returned yet
   return (<div classname="container">
      ...
    </div>);
}

score:0

i would put the itemapi.getallitems() in component's constructor. once the items arrive, no matter when, the state will be updated and this will trigger render().

score:0

create method 'asyncupdate(data) { this.setstate(data) }' in constructor set 'this.asyncupdate = this.asyncupdate.bind(this)'

and after your promise call trigger 'this.asyncupdate(promiseddata)'

should help

score:0

from the docs: componentwillmount() is invoked immediately before mounting occurs. it is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. avoid introducing any side-effects or subscriptions in this method. you should be able to make your request in componentdidmount(). this ensures a rerender when the state changes. if it's still empty, there's a chance that your map in your render is returning an empty array. make sure you are properly formatting the item that is returned from your api. there's a chance the response is of the form { items: [] }.

score:0

according to the react documentation calling apis is best done in componentdidmount().

that in combination with the answer from benjamin will give you the best implementation.


Related Query

More Query from same tag